C++
C++で文字列を置換する
文字列中の指定した部分文字列を、別の指定した文字列に置き換えます。サンプルでは、コマンドライン引数の内、1つ目の文字列に含まれる2つ目の引数で指定した部分文字列を、3つ目の引数で指定した文字列に置き換えて表示します。
replace_string.cpp
#include <iostream> // cout, endl
/**
* @brief Replace substring of string
*
* @param[in] target Target string, substring of this is replaced
* @param[in] from "from" is changed to "to".
* @param[in] to "from" is changed to "to".
* @return Replaced string
*/
std::string replaceString(const std::string target,
const std::string from,
const std::string to) {
std::string result = target;
std::string::size_type pos = 0;
while(pos = result.find(from, pos), pos != std::string::npos) {
result.replace(pos, from.length(), to);
pos += to.length();
}
return result;
}
// Main function for usage example
// First command line argment is target string to replace
// Second command line argument is replaced to Third command line argument
int main(int argc, char *argv[]) {
if (argc != 4) {
std::cout << "Please specify 3 strings!" << std::endl;
return -1;
}
std::string target = std::string(argv[1]);
std::string from = std::string(argv[2]);
std::string to = std::string(argv[3]);
std::cout << replaceString(target, from, to) << std::endl;
return 0;
}
実行結果
$ replace_string.cpp -o replace_string
$ ./replace_string "IhogelovehogePanda.hoge" "hoge" " "
I love Panda.