C++ 文字列で特定の文字を置き換える方法
C++では、文字列は std::string クラスで表現できます。文字列内の特定の文字を置換するには、 std::replace 関数を使用できます。
以下にサンプルコードを掲載します。
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "Hello, World!";
char oldChar = 'o';
char newChar = '*';
std::replace(str.begin(), str.end(), oldChar, newChar);
std::cout << str << std::endl;
return 0;
}
上記のコードでは、文字列 str を定義し、置換対象となる文字 oldChar と置換後の文字 newChar を指定しています。その後、 std::replace 関数を使用して文字列内のすべての oldChar 文字を newChar 文字に置換しています。最後に、置換後の文字列を出力しています。
上記のコードを実行すると「Hell*, W*rld!」が出力され、文字列内のすべてのo文字が*文字に置換されていることが確認できる。
お役に立てれば幸いです!