C
C言語には、文字列を検索する strstr 関数がある。
C言語関数辞典 : strstr
http://www.c-tipsref.com/reference/string/strstr.html
これを使って、
文字列「foo bar fiz」から target「bar」を探して、
replace「xyz」に置換する例を示す。
手順は、下記のようになる。
(1) target「bar」より先頭側の文字列「foo」を得る。
(2) target「bar」より末尾側の文字列「fiz」を得て、tail に保存する。
(3) 先頭側「foo」 replace「xyz」tail「fiz」を連結して、
「foo xyz fiz」にする。
ソースコードだけでは、ポインタの動きがわかりにくいので、図に示した。
char src[] = "foo bar fiz"; char *target = "bar"; char *replace = "xyz"; char work[100]; char tail[100]; char result[100]; printf("src: %s\n", src); // "foo bar fiz"; strcpy(work, src); // work は下図 (1)の状態 char *p; // 文字列 work から文字列 targetを探す // 探し出した文字列へのポインタを返す // taget「bar」の先頭「b」の位置 p = strstr(work, target); // ポインタ は下図 (2)の状態 検出した位置に文字列終端 '\0' を挿入する *p = '\0'; // work は下図 (3)の状態 printf("work: %s \n", work); // "foo"; ポインタを検出位置から target の文字数分に移動する p += strlen(target); // ポインタ は下図 (4)の状態 // 文字列 tail に保存する strcpy(tail, p); printf("tail: %s \n", tail); // "fiz"; // 文字列 work, replace, tail を連結する strcpy(result, work); // "foo"; strcat(result, replace); // "foo xyz"; strcat(result, tail); // "foo xyz fiz"; printf("result: %s\n", result); // "foo xyz fiz";
参考 : 文字列の置換
https://dev.grapecity.co.jp/support/powernews/column/clang/049/page03.htm
サンプルコードは githubに公開した
https://github.com/ohwada/MAC_cpp_Samples/tree/master/string/c_src
C++
C++ には、 文字列を検索するメソッド string::find と、 文字列を置換するメソッド string::replace がある。
C++日本語リファレンス : basic_string find
https://cpprefjp.github.io/reference/string/basic_string/find.html
C++日本語リファレンス : basic_string replace
https://cpprefjp.github.io/reference/string/basic_string/replace.html
これを使って、 文字列「foo bar fiz」から target「bar」を探して、 replace「xyz」に置換する例を示す。
std::string src("foo bar fiz"); std::string target("bar"); std::string replace ("xyz"); // 文字列 src から文字列 targetを探す // 探し出した文字列の位置を返す // taget「bar」の先頭「b」の位置 std::string::size_type pos = src.find(target); std::string result = src; // 検出位置から target の文字数分を replace に置換する result.replace(pos, target.length(), replace);
全ての文字列を置換する
boost ライブラリ使うのが便利。
Boost逆引きリファレンス : 文字列操作
https://boostjp.github.io/tips/string_algo.html
std::string result = boost::algorithm::replace_all_copy(src, target, replace );