標準ライブラリではstringクラスという便利なクラスを使うことができます。
このクラスを使うにはstringをインクルードする必要があります。
stringクラスを使うと文字列をかなり直感的に扱うことができます。
代入は「=」、文字列の連結は「+」演算子で実現できます。
// string01.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s, t, u;
s = "粂井";
t = "康孝";
u = s + t;
cout << u << endl;
return 0;
}
実行結果は左の図のようになります。文字列が連結されているのが
わかります。
文字列ばかりでなく、文字も連結することができます。
string s = "ABC"; cout << s + 'D' << endl;というようなこともできます。
また、
string s = "BCD", t; t = 'A' + s;というように「文字」+「stringオブジェクト」も可能です。では、 次の演算はどうでしょうか。
string s, t; s = "CDE"; t = 'A' + 'B' + s;これは、だめですね。しかし、次のようにすると可能です。
string s, t;
s = "CDE";
t = 'A' + ('B' + s);
次に文字列の比較に「==」演算子が使えます。
// string02.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string password;
cout << "パスワード:";
cin >> password;
if (password == "ABC")
cout << "OK!" << endl;
else
cout << "NO!" << endl;
return 0;
}
当然ですが、strcmp関数でstringオブジェクトと文字列の比較は行えません。
また、strcat関数でstringオブジェクトと文字列の連結は行えません。その他stringオブジェクトについては「!=」「>」「<」「>=」「<=」「+=」などの 演算子が使えます。いろいろ実験してみてください。
Update Jun/28/2002 By Y.Kumei