std::string: 安全な文字列操作

C文字列の危険を回避。メモリ管理も自動。

std::string
動的サイズの文字列クラス。
string_view
コピーなしの文字列参照。
npos
検索失敗を示す定数。

文字列基礎

ビーズのネックレス (Necklace)

C言語の文字列は「床に散らばったビーズ(char型)」で、管理が大変でした。std::stringは「糸に通されたネックレス」です。ビーズが散らばることもなく、長さも自動で管理され、簡単に追加や削除ができます。

std::string はメモリ確保、解放、リサイズを全自動で行います。`+` 演算子で直感的に連結でき、バッファオーバーフローの心配もありません。現代C++では `char*` を使う理由はほぼありません。

std::string Operations
#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"); // 6
if (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::string
std::string s = "hello";
s += " world"; // 安全

高度な操作

Conversion, string_view, format
// 変換
std::string num = std::to_string(42);
int n = std::stoi("42");
double d = std::stod("3.14");
// C++20 starts_with / ends_with
if (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に格納する関数を作成してください。

次のステップ