ゲームが作れるようになるまでがんばる日記

ゲーム制作のことを中心にゲームに関することを書いています

stringのfind,rfind

stringのメンバ関数find(),rfind()は文字列を検索するもの。
find()は指定した文字列が最初にあらわれたインデックス位置を返し、rfind()は逆に最後にあらわれた位置を返す。
そして、指定した文字列が見つからない時には npos を返す。

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str1("This is a test. This is a test2.");

    int i = str1.find("test");
    cout << i << endl;

    i = str1.rfind("test");
    cout << i << endl;

    i = str1.find("abc");
    if (i == string::npos) cout << "Not Found." << endl;
}

実行結果
10
26
Not Found.