stringはC++のクラスという仕組みを使った便利な文字列を扱うクラスです。
厳密には型ではないので、注意
伝統的なC/C++の世界では、文字配列にアスキーコードをしまい込んで、配列の最後に終端文字``` '\0' ```をつけることで、文字列型の代わりに使います。

"char配列と文字列型"
#include <iostream>
#include <string>
 
using namespace std;
 
int main()
{
	//文字配列を使った文字列の表現=文字配列+終端文字
	//長さは自分で、宣言するか、リテラル初期化で予測決定させる
	//文字列の長さはstrlenで取得する
	//長さは初期化した時の長さで固定
	//文字列の比較はできない
	const int STR_LENGTH = 8;
	const int MAX_STR_LENGTH = 256;
	//"abcdef" < -文字列リテラル
	//char mj[STR_LENGTH] = { 'a','b','c','d','e','f','g','\0' };
	//char mj[STR_LENGTH] = "abcdefg";
	char mj[] = "abc"; //={ 'a','b','c','\0'}
	char text[] = "def";//={'d','e','f','\0'}
	char result[MAX_STR_LENGTH] = "";
 
	//resultにmjとtextをつなげた文字列を作ってみよう
	//
 
	//'\0'は終端文字(ナル文字)
	int len1 = strlen(mj);
	int len2 = strlen(text);
	cout << "mj length = " << len1 << endl;
	cout << "text length = " << len2 << endl;
	//for (int i = 0; i < len1+len2; i++)
	//{
	//	if (i < len1)
	//	{
	//		result[i] = mj[i];
	//	}
	//	else
	//	{
	//		result[i] = text[i - len1];
	//	}
	//}
	//result[len1 + len2] = '\0';
	strcat_s(result, mj);
	strcat_s(result, text);
	//if(result == "abcdef")これはできない
	if (strcmp(result, "abcdef") == 0)
	{
		cout << "合体成功" << endl;
	}
	else
	{
		cout << "ダーク悪魔誕生" << endl;
	}
	cout << result;//abcdef
 
	cout << endl;
 
	//string str = "moji retsu";
	//cout << str << endl;
	//     0     1     2     3                                   9
	//['m'] ['o'] ['j'] ['i'] [' '] ['r'] ['e'] ['t'] ['s'] ['u']
	//for (int i = 0; i < str.size(); i++)
	//{
	//	if (str[i] == ' ')
	//		cout << "SPACE" << endl;
	//	else
	//		cout << str[i] << endl;
	//	getchar();
	//}
}
  • game-engineer/classes/2023/game-programing-1/first-term/6/06-28-5.txt
  • 最終更新: 3年前
  • by root