template <class charT, class traits = char_traits<charT>, class Allocator = allocator<charT>> class basic_string using string = basic_string<char>; using u8string = basic_string<char8_t>; // C++20 using u16string = basic_string<char16_t>; // C++11 using u32string = basic_string<char32_t>; // C++11 using wstring = basic_string<wchar_t>;
#include <string> using namespace std; string 変数名;
= + += == != < <= > >= << >> []
#include <iostream> #include <string> using namespace std; int main() { char str[10]; string str1 = "abcde"; string str2 = str1, str3 = "bcdef"; string::iterator it1, it2; // 文字列のコピー str1.copy(str, 3, 2); str[3] = '\0'; cout << "コピーされた結果 " << str << endl; // 文字列の比較 cout << "比較 str1 = " << str1 << ", str2 = " << str2 << ", str3 = " << str3 << endl; if (str2 == str1) cout << " str2 == str1\n"; if (str2 <= str2) cout << " str2 <= str3\n"; // 文字列の結合 str1 += (" " + str2); cout << "文字列の結合結果: " << str1 << endl; // 部分文字列 cout << str1 << " の 4 文字目から 5 文字\n"; cout << " " << str1.substr(3, 5) << endl; cout << " "; for (int i1 = 3; i1 < 8; i1++) cout << str1[i1]; cout << endl; cout << " "; for (int i1 = 3; i1 < 8; i1++) cout << str1.at(i1); cout << endl; const char *c_str = str1.c_str(); cout << " "; for (int i1 = 3; i1 < 8; i1++) cout << c_str[i1]; cout << endl; // 検索 cout << str1 << " から文字列 cd の検索結果: " << str1.find("cd") << endl; // 挿入 cout << "挿入(元の文字列: " << str1 << ")\n"; str2 = "-+*+-"; str3 = str1; cout << " " << str3.insert(2, str2, 0, 3) << endl; str3 = str1; it1 = str3.begin() + 2; str3.insert(it1, 3, '*'); cout << " " << str3 << endl; // 削除 cout << "削除(元の文字列: " << str1 << ")\n"; str3 = str1; cout << " " << str3.erase(2, 3) << endl; str3 = str1; it1 = str3.begin() + 2; it2 = it1 + 3; str3.erase(it1, it2); cout << " " << str3 << endl; // 置換 cout << "置換(元の文字列: " << str1 << ")\n"; str2 = "-+*+-"; str3 = str1; cout << " " << str3.replace(3, 5, str2, 0, 3) << endl; str3 = str1; it1 = str3.begin() + 3; it2 = it1 + 5; cout << " " << str3.replace(it1, it2, str2) << endl; // 交換 cout << "交換\n"; str2 = "-+*+-"; cout << " " << str1 << " " << str2 << endl; str1.swap(str2); cout << " " << str1 << " " << str2 << endl; return 0; }
コピーされた結果 cde 比較 str1 = abcde, str2 = abcde, str3 = bcdef str2 == str1 str2 <= str3 文字列の結合結果: abcde abcde abcde abcde の 4 文字目から 5 文字 de ab de ab de ab de ab abcde abcde から文字列 cd の検索結果: 2 挿入(元の文字列: abcde abcde) ab-+*cde abcde ab***cde abcde 削除(元の文字列: abcde abcde) ab abcde ab abcde 置換(元の文字列: abcde abcde) abc-+*cde abc-+*+-cde 交換 abcde abcde -+*+- -+*+- abcde abcde
#include <iostream> #include <string> using namespace std; int main() { cout << "stoi \"120\" to " << stoi("120") << endl; cout << "stod \"3.141592654\" to " << stod("3.141592654") << endl; cout << "to_string 120 \"" << to_string(120) << "\" 3.141592654 \"" << to_string(3.141592654) << "\"\n"; return 0; }
stoi "120" to 120 stod "3.141592654" to 3.14159 to_string 120 "120" 3.141592654 "3.141593"
菅沼ホーム | 本文目次 | 演習問題解答例 | 付録目次 | 索引 |