string的find()函數用於找出字母在字符串中的位置。
find(str,position)
find()的兩個參數:
str:是要找的元素
position:字符串中的某個位置,表示從從這個位置開始的字符串中找指定元素。
可以不填第二個參數,默認從字符串的開頭進行查找。
返回值為目標字符的位置,當沒有找到目標字符時返回npos。
例1:找到目標字符的位置
string s = "hello world!"; cout << s.find("e") << endl;
結果為:1
例2:未找到目標字符
string s = "hello world!"; if (s.find("a") == s.npos) { cout << "404 not found" << endl; }
結果為:404 not found
例3:指定查找位置
string s = "hello world!"; cout << s.find("l",5) << endl;
結果為:9
從空格開始(包含空格)的后半部分字符串中尋找字符"l",結果找到了world中的"l"在整個字符串中的位置
找到目標字符在字符串中第一次出現和最后一次出現的位置
例4:
string s = "hello world!"; cout << "first time occur in s:"<<s.find_first_of("l") << endl; cout << "last time occur in s:" << s.find_last_of("l") << endl;
結果為:
first time occur in s:2
last time occur in s:9
反向查找:
例5:
string s = "hello world!"; cout << s.rfind("l") << endl;
結果為:9
即從后往前第一次出現"l"的位置
參考一下:https://www.cnblogs.com/wkfvawl/p/9429128.html