404 Not Found

404 Not Found


nginx

文字列の操作

[第]19[課では、] string [の基本操作] を学びました。

[実際の場面では]、[文字を削除する][文字を挿入する][文字列を比較する][数値を文字列に変換する]……といった操作が必要になる場合があります。

[このレッスン]では、[stringの] [応用操作]を[学びましょう]。


1. [編集]文字列

(1) 1.1 [文字の削除](erase)

[文法]:

▶ サンプル 2: codeexample (難易度 ⭐)

CPP
string.erase(, );
▶ 試してみよう

例:

CPP
#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)

[文法]:

TEXT
string.insert(, );

例:

CPP
#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)

CPP
#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() 関数は[提供できる]ものです。

基本的な使い方

CPP
#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;
}

[戻る]値:

💡 [ヒント]: [実際には]、==!=<>を[直接使用]する方が、[文字列]を使うよりも[より直感的]です。[これらの演算子]の使用をお勧めします。



3. 文字列と[数値の相互変換]

(1) 3.1 [数値から文字列への変換]string(to_string)

CPP
#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");

例:

CPP
#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 [下付き文字]

CPP
#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、[推奨])

CPP
#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: [実装]「[検索と置換]」[機能] (難易度 ⭐⭐)

CPP
#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.

💡 [重要]: [置換後]、[新しく挿入された]文字列を[スキップする必要がある]。そうしないと、[新しい]文字列に[元の]文字列が含まれている場合、無限ループに陥る。


❓ よくある質問

Q [なぜ文字列を] 走査する際に [size_t] を使い、[int] では[いけない]のか?
A [なぜなら] string::length() [が返すのは] size_t([符号なし整数])だからです。[もし] int [を使用すると]、[比較時に] 警告([符号付き] 対 [符号なし])が発生する可能性があります。
Q stoi [変換に失敗した場合はどうなるか]?
A std::invalid_argument 例外が[スローされる]。

📖 まとめ


📝 練習問題

  1. 初心者(難易度 ⭐): [ある]プログラムを作成し、[ユーザーに][1つの]文字列を入力させ、[その中のすべてのスペースを削除する]ようにする。
World, this is C++!:HelloWorld,thisisC++!
  1. 中級(難易度 ⭐⭐): [ある]プログラムを作成し、[ユーザーに][1つの]文字列を入力させ、[それが]「[回文]」であるかどうかを判定する([前から読んでも後ろから読んでも同じ]文字列のこと。[例]「level」、「radar」など)。
  1. 上級(難易度 ⭐⭐⭐): [プログラム]を作成し、[「簡単な暗号化」/[復号化]]を[実装]する:

6. 🚀 次は

[stringの] [高度な操作] を学んだところで、[次は] フェーズ4(ポインタ[と]参照) に入ります。[これは] C++ [で最も]「[挫折]」を招きやすい[一方で、最も重要な部分]です――[メモリの仕組みを] [理解してこそ、効率的な] コードが書けるのです!

Web-Tutorial.com

Web-Tutorial 技術チーム

複数の開発者によって共同維持されているプログラミングチュートリアルプラットフォーム。各チュートリアルは専門分野の開発者が執筆・レビューしています。正確で信頼性の高いコンテンツを目指しています — 問題を見つけた場合はお知らせください。

100%