std::string: 安全な文字列操作
C文字列の危険を回避。メモリ管理も自動。
std::string
動的サイズの文字列クラス。
string_view
コピーなしの文字列参照。
npos
検索失敗を示す定数。
文字列基礎
std::string はメモリ確保、解放、リサイズを全自動で行います。`+` 演算子で直感的に連結でき、バッファオーバーフローの心配もありません。現代C++では `char*` を使う理由はほぼありません。
#include <string>
std::string s = "Hello";
// 連結s += " World"; // "Hello World"auto s2 = s + "!"; // "Hello World!"
// アクセスchar c = s[0]; // 'H'char safe = s.at(0); // 範囲チェック付き
// 検索size_t pos = s.find("World"); // 6if (pos != std::string::npos) { // 見つかった}
// サブストリングauto sub = s.substr(0, 5); // "Hello"実行結果
s = "Hello World"\ns.find("World") = 6\ns.substr(0, 5) = "Hello" Bad
// ❌ Bad: C文字列を直接操作char buf[100];strcpy(buf, "hello");strcat(buf, " world"); // バッファオーバーフロー危険Good
// ✅ Good: std::stringstd::string s = "hello";s += " world"; // 安全高度な操作
// 変換std::string num = std::to_string(42);int n = std::stoi("42");double d = std::stod("3.14");
// C++20 starts_with / ends_withif (s.starts_with("Hello")) { }if (s.ends_with("!")) { }
// string_view (C++17, コピーなし参照)void print(std::string_view sv) { std::cout << sv << "\n";}print("Hello"); // 一時オブジェクトを作らない
// 書式設定 (C++20 format)auto msg = std::format("Name: {}, Age: {}", name, age); Tip: 関数引数は const std::string& か std::string_view で。
合格ライン
find と npos を使える
string_view の利点を説明できる
参考リンク
演習課題
課題1: 文字列操作
文字列内の特定の単語を別の単語に置換する関数を作成してください。
課題2: 文字列分割
デリミタで文字列を分割してvectorに格納する関数を作成してください。