文字列の操作
[第]19[課では、] string [の基本操作] を学びました。
[実際の場面では]、[文字を削除する]、[文字を挿入する]、[文字列を比較する]、[数値を文字列に変換する]……といった操作が必要になる場合があります。
[このレッスン]では、[stringの] [応用操作]を[学びましょう]。
1. [編集]文字列
(1) 1.1 [文字の削除](erase)
[文法]:
▶ サンプル 2: codeexample (難易度 ⭐)
string.erase(, );
例:
#include iostream
#include string
int main() {
std::string text = "Hello, World!";
// 5 7 (", World")
text.erase(5, 7);
std::cout << text << std::endl; // Hello!
return 0;
}
💡 [ヒント]: [引数を1つだけ指定した場合]、erase(pos) [は、] pos [から末尾までのすべての文字を削除します]。
(2) 1.2 [文字の挿入](insert)
[文法]:
string.insert(, );
例:
#include iostream
#include string
int main() {
std::string text = "Hello!";
// 5 " World"
text.insert(5, " World");
std::cout << text << std::endl; // Hello World!
return 0;
}
(3) 1.3 [クリア]文字列(clear)
#include iostream
#include string
int main() {
std::string text = "Hello";
text.clear(); // ...
std::cout << ":" << text.length() << std::endl; // 0
std::cout << ":" << text.empty() << std::endl; // 1(true)
return 0;
}
💡 [ヒント]: empty() 関数[は、]文字列[が空かどうかを判定するために使用されます]([空の場合は] true、[つまり] 1 を返します)。
2. [比較]string(compare)
==、!=、<、> は、[比較的] 文字列よりも[より詳細な情報]ですが、compare() 関数は[提供できる]ものです。
基本的な使い方
#include iostream
#include string
int main() {
std::string s1 = "apple";
std::string s2 = "banana";
int result = s1.compare(s2);
if (result == 0) {
std::cout << "s1 s2" << std::endl;
} else if (result < 0) {
std::cout << "s1 s2" << std::endl; // ...
} else {
std::cout << "s1 s2" << std::endl;
}
return 0;
}
[戻る]値:
0:[2つの]文字列[が等しい]< 0:[呼び出し元が引数より小さい]> 0:[呼び出し元が引数より大きい]
💡 [ヒント]: [実際には]、==、!=、<、>を[直接使用]する方が、[文字列]を使うよりも[より直感的]です。[これらの演算子]の使用をお勧めします。
3. 文字列と[数値の相互変換]
(1) 3.1 [数値から文字列への変換]string(to_string)
#include iostream
#include string
int main() {
int age = 25;
double price = 19.99;
std::string ageStr = std::to_string(age);
std::string priceStr = std::to_string(price);
std::cout << ":" << ageStr << std::endl;
std::cout << ":" << priceStr << std::endl;
return 0;
}
出力:
💡 [ヒント]: to_string() [浮動小数点数の変換時]、[6桁の小数]が[保持されます]。[形式を制御したい場合は]、std::ostringstream [または] std::format(C++20)を[使用してください]。
(2) 3.2 文字列[数値への変換](stoi、stod)
| 関数 | [作用] | 例 |
|---|---|---|
std::stoi(str) |
文字列 → 整数 | int x = std::stoi("123"); |
std::stol(str) |
文字列 → long | long x = std::stol("123"); |
std::stoll(str) |
文字列 → long long | long long x = std::stoll("123"); |
std::stof(str) |
文字列 → 浮動小数点数 | float x = std::stof("3.14"); |
std::stod(str) |
文字列 → 実数 | double x = std::stod("3.14"); |
例:
#include iostream
#include string
int main() {
std::string numStr = "123";
std::string priceStr = "19.99";
int num = std::stoi(numStr);
double price = std::stod(priceStr);
std::cout << "num = " << num << std::endl;
std::cout << "price = " << price << std::endl;
return 0;
}
⚠️ [注意]: [もし]string[が有効な数値形式でない場合]、stoi / stod [は]例外を[スローします]。[後ほど、] try-catch を使って[これを処理する]方法を学びます。
4. [文字列の走査]
(1) 4.1 [下付き文字]
#include iostream
#include string
int main() {
std::string text = "Hello";
for (size_t i = 0; i < text.length(); i++) {
std::cout << text[i] << " ";
}
std::cout << std::endl;
return 0;
}
(2) 4.2 [適用範囲] for(C++11、[推奨])
#include iostream
#include string
int main() {
std::string text = "Hello";
for (char c : text) {
std::cout << c << " ";
}
std::cout << std::endl;
return 0;
}
💡 [ヒント]: [範囲] for [より簡潔]、[かつ書き間違いにくい]ループ条件。
5. 演習:[シンプルなテキストエディタ]
▶ サンプル 1: [実装]「[検索と置換]」[機能] (難易度 ⭐⭐)
#include iostream
#include string
int main() {
std::string text = "I like C. C is powerful.";
std::string oldStr = "C";
std::string newStr = "C++";
size_t pos = 0;
while ((pos = text.find(oldStr, pos)) != std::string::npos) {
text.replace(pos, oldStr.length(), newStr);
pos += newStr.length(); // ...
}
std::cout << ":" << text << std::endl;
return 0;
}
出力:
like C++. C++ is powerful.
💡 [重要]: [置換後]、[新しく挿入された]文字列を[スキップする必要がある]。そうしないと、[新しい]文字列に[元の]文字列が含まれている場合、無限ループに陥る。
❓ よくある質問
string::length() [が返すのは] size_t([符号なし整数])だからです。[もし] int [を使用すると]、[比較時に] 警告([符号付き] 対 [符号なし])が発生する可能性があります。std::invalid_argument 例外が[スローされる]。📖 まとめ
erase()[文字を削除]、insert()[文字を挿入]、clear()[文字列を空にする]compare()[比較]文字列([ただし、直接==、!=[などの]演算子を使用することを推奨します])to_string()[数字を]文字列に変換stoi()/stod()[文字列を]数値[に変換する]- [文字列の反復処理][範囲] for(C++11)(推奨)
📝 練習問題
- 初心者(難易度 ⭐): [ある]プログラムを作成し、[ユーザーに][1つの]文字列を入力させ、[その中のすべてのスペースを削除する]ようにする。
World, this is C++!:HelloWorld,thisisC++!
- 中級(難易度 ⭐⭐): [ある]プログラムを作成し、[ユーザーに][1つの]文字列を入力させ、[それが]「[回文]」であるかどうかを判定する([前から読んでも後ろから読んでも同じ]文字列のこと。[例]「level」、「radar」など)。
- [ヒント]:[2つの]ポインタ([またはインデックス])を使い、[1つは先頭から末尾へ]、[もう1つは末尾から先頭へ]、[1つずつ比較]することができます。
- 上級(難易度 ⭐⭐⭐): [プログラム]を作成し、[「簡単な暗号化」/[復号化]]を[実装]する:
-
[暗号化ルール]:[各文字の] ASCII [コードに] 3 を加える([例]
'A'→'D') -
[解読ルール]:[各文字の] ASCII [コードから] 3 [を引く]
-
[ユーザーに]文字列を入力させ、[まず暗号化してから復号化]し、[結果]を出力する
-
[検索]:find/rfind/find_first_of [部分文字列]
-
[切り取り]:substr(pos, count) [部分文字列の抽出]
-
[置換]:replace(pos, count, str) [一部の内容を置換]
-
[挿入]/[削除]:insert/erase [動的変更]string
-
タイプ[変換]:stoi/stod/to_string [文字列と数値間の変換]
6. 🚀 次は
[stringの] [高度な操作] を学んだところで、[次は] フェーズ4(ポインタ[と]参照) に入ります。[これは] C++ [で最も]「[挫折]」を招きやすい[一方で、最も重要な部分]です――[メモリの仕組みを] [理解してこそ、効率的な] コードが書けるのです!



