それではstringの使い方について説明します。
まずは、stringの初期化について書きます。
<sample program cpp006-01>
#include <iostream> #include <string> int main() { std::string str = "Hello"; std::cout << "str = " << str << std::endl; str = "World"; std::cout << "str = " << str << std::endl; return 0; } |
<実行結果>
str = Hello str = World 続行するには何かキーを押してください・・・
std::string str = "Hello"; |
C言語でも変数宣言と同時に初期値を代入する方法がありました。
stringも宣言と同時に文字列を代入する事が出来ます。
str = "World"; |
これはC言語の文字列では出来なかった事です。
配列に文字列を代入する事が出来なかったので、C言語では、
char str[10]; strcpy(str, "World"); |
このようにしなければなりませんでした。
次は文字列操作について書きましょう。
<sample program cpp006-02>
#include <iostream> #include <string> int main() { std::string str1; std::string str2; std::string str3; str1 = "Hello"; str2 = str1; std::cout << "str2 = " << str2 << std::endl; str3 = str2 + " "; str3 += "World"; std::cout << "str3 = " << str3 << std::endl; return 0; } |
<実行結果>
str2 = Hello str3 = Hello World 続行するには何かキーを押してください・・・
文字列のコピーは単純に「=」で出来ます。
連結についても「+演算子」「+=演算子」で出来るようになっています。
文字列の比較についても「==」「!=」で可能です。
<sample program cpp006-02>
#include <iostream> #include <string> int main() { std::string str1 = "Hello"; std::string str2 = "Hello"; std::string str3 = "World"; if (str1 == str2) { std::cout << "同じ" << std::endl; } if (str1 != str3) { std::cout << "違う" << std::endl; } return 0; } |
<実行結果>
同じ 違う 続行するには何かキーを押してください・・・
直観的で非常に分かりやすいですね。