STL で文字列の検索

STL の string を使った文字列の検索と置換です。

前田稔(Maeda Minoru)の超初心者のプログラム入門

文字列の検索

  1. STL の string で文字列を定義して、キーワードで検索します。
    str.find("red",p) が文字列を検索するメソッドです。
    str が STL の string Object Class で、メンバー関数 find() を呼び出します。
    "red" が検索する文字列です。
    p は str の先頭からのオフセットです。
    見つからないときは -1 がリターンされます。
    /*★ string search     前田  稔 ★*/
    #include <stdio.h>
    #include <string>
    using namespace std;
    
    int main()
    {   string  str= "redred black red white red  gray";
        int     p;
    
        for(p=0; (p=str.find("red",p))!=-1; p+=3)
            printf("pos=%d\n", p);
        return 0;
    }
    
  2. 見つかった位置を printf() で印字しています。
    プログラムの実行結果です。
    C:\DATA\Cpp\STL>StrSearch
    pos=0
    pos=3
    pos=13
    pos=23
    

文字列の置き換え

  1. STL の string を使って "red" を "purple" に置き換えてみましょう。
    str.find("red",p) で "red" を検索します。
    "red" が見つかったとき str.replace(p,3,"purple"); で "purple" に置き換えます。
    p は str の先頭からのオフセットです。
    p から始まる 3 文字を "purple" に置き換えます。
    /*★ string replace     前田  稔 ★*/
    #include <stdio.h>
    #include <string>
    using namespace std;
    
    int main()
    {   string  str= "red black white red  blue gray yellow";
        int     p;
    
        for(p=0; (p=str.find("red",p))!=-1; p+=3)
            str.replace(p,3,"purple");
        printf("%s\n", str.data());
        return 0;
    }
    
  2. プログラムの実行結果です。
    C:\DATA\Cpp\STL>StrReplace
    purple black white purple  blue gray yellow
    
  3. char 配列を使ったプログラムは 文字列の検索 を参照して下さい。
    Program Guid でストリング関係のページを抜粋しています。

超初心者のプログラム入門(C/C++)