#include下的str.find()函數

str.find(ss)//返回字符串ss在str中的位置

str.find(ss,num) //在str[num]~str[n-1]範圍內查找並返回字符串ss在str的位置

str.rfind(ss,num)////在str[0]~str[num]範圍內查找並返回字符串ss在str的位置(reverse)

例子:

#include <iostream>
using namespace std;
int main()
{
    //string str("abcabcabcd");
    string str="abcacbabcd";
    string::size_type pos=0;
    cout << str.find("a",2) << endl;
    cout << str.rfind("c",5) << endl;//?如果出現多個c,好像返回最後一個
    cout << str.find("bc") << endl;
    cout << str.find("za") << endl;  // 找不到,返回string::npos
    return 0;
}

結果:

 

 找出子字符串所有的出現位置

例子:

#include <iostream>
using namespace std;
int main()
{
    //string str("abcabcabcd");
    string str="abcabcbabcd";
    string::size_type pos=0;  //注意
    while((pos=str.find("abc",pos))!=std::string::npos)
    {
        cout<<pos<<endl;
        pos++;
    }
    return 0;
}

結果:

 

整理的很多的一篇文章:https://www.renfei.org/blog/introduction-to-cpp-string.html 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章