C++string中find,find_first_of和find_last_of的用法

1.find

str.find(str1)

说明:从前向后在str中找到str1,并返回其索引值,否则返回-1

2.find_first_of

str.find_first_of(str1)

说明:从前向后在str中找到str1,并返回其索引值,否则返回-1

3.find_last_of

str.find_last_of(str1)

说明:从后向前在str中找到str1,并返回其从后向前的索引值,否则返回-1

#include<iostream>
using namespace std;
               
int main(void) 
{              
    string s = "一蓑烟雨任平生。";
    int len = s.size();
    int count = s.size() / string("一").size();
    cout << "len = " << len << ", count = " << count << endl;
    cout << "一: pos = " << s.find("一") << endl;
    cout << "一: pos = " << s.find_first_of("一") << endl;
    cout << "一: pos = " << s.find_last_of("一") << endl;
    int pos = s.find("一", 1);
    cout << "pos:" << pos << endl;
    cout << "。: pos = "s.find("。") << endl;                                                                                                     
    cout << "。: pos = "s.find_last_of("。") << endl;
    return 0;  
}      

结果:
结果:

len = 24, count = 8
一: pos = 0
一: pos = 0
一: pos = 22
pos:-1
0
2

总结:

在判断以中文字符结尾的字符串的时候最好不要用find_last_of这个函数,容易出错。如上例所示如果判断某句话是否以句号“。”结束,则需要判断返回值是否2,而不是判断返回值加上句号本身的长度等于该字符串的长度。

猜你喜欢

转载自www.cnblogs.com/zh20130424/p/11099932.html