C++で文字列内から文字を検索する方法とは
C++では文字列内の文字を見つけるために以下の方法を使用できます:
- 見つける
- 見つける
string_name.find(char_to_find);
String_nameで探す文字がchar_to_findです。見つかった場合、文字の位置を返します。見つからない場合はstring::nposを返します。
- find_first_of()
- 先頭文字を検索する
string_name.find_first_of(characters);
string_nameを検索する文字列で、charactersは検索する文字の一覧が含まれた文字列です。見つかった場合は文字の位置を、見つからない場合はstring::nposを返します。
- 文字列をループ処理する: 文字列内のすべての文字をループで繰り返し、ターゲット文字と比較することができます。一致する文字が見つかった場合、位置を記録したり、その他のアクションを実行します。
以下はサンプルコードで、上記3つのメソッドの使い方を示す:
#include <iostream>
using namespace std;
int main() {
string str = "Hello, World!";
char target = 'o';
// 使用find()函数
size_t pos = str.find(target);
if (pos != string::npos) {
cout << "Found at position: " << pos << endl;
} else {
cout << "Not found!" << endl;
}
// 使用find_first_of()函数
pos = str.find_first_of("aeiou");
if (pos != string::npos) {
cout << "Found vowel at position: " << pos << endl;
} else {
cout << "No vowel found!" << endl;
}
// 使用循环遍历字符串
for (size_t i = 0; i < str.length(); i++) {
if (str[i] == target) {
cout << "Found at position: " << i << endl;
break;
}
}
return 0;
}
ネイティブな日本語で言い換えた文は「これを日本語に自然に言い換えると」です。
Found at position: 4
Found vowel at position: 1
Found at position: 4
この例では文字列「Hello, World!」とターゲット文字’o’ を使って検索しています。1つめの方法は find() 関数を使用して最初に出現する ‘o’ の位置を検索しています。2つめの方法は find_first_of() 関数を使用して最初に出現する母音文字の位置を検索しています。3つめの方法は文字列を走査して最初に出現する ‘o’ の位置を検索しています。