cplusplus reference–string
cppreference–string
string类的字符串操作
- find – 在字符串中查找内容
void test12()
{
string str = "12345abcd123456789";
string str2 = "123456789";
size_t pos = str.find(str2); //9 第九个位置
pos = str.find("abc", 5, 3); //5 第五个位置
pos = str.find('a'); // 5 第五个位置
pos = str.find("xyz"); //4294967295 即-1 未找到
}
void test13()
{
//正向查找
string str = "http://www.cplusplus.com/reference/string/string/substr/";
size_t pos = str.find("://");
if (pos != string::npos)
{
size_t pos2 = str.find("/", pos + 3);
if (pos2 != string::npos)
{
pos += 3;
string sub = str.substr(pos, pos2 - pos);
cout << sub << endl; //www.cplusplus.com
}
}
//反向查找
string str2 = "test.txt.tar.gz.cpp";
size_t pos2 = str2.rfind(".");
if (pos != string::npos)
{
cout << str2.substr(pos2 + 1); //cpp
}
}
- find_first_of – 查找字符串中的字符,搜索与其参数中指定的任何字符匹配的第一个字符
- find_last_of – 查找字符串中的字符,搜索与其参数中指定的任何字符匹配的最后一个字符
- find_first_not_of – 搜索字符串,查找与其参数中指定的任何字符不匹配的第一个字符
- find_last_not_of – 搜索与参数中指定的任何字符不匹配的最后一个字符的字符串
void test14()
{
string str = "1234abcd123abc";
size_t pos;
pos = str.find_first_of("abc",0); //4 匹配第一个字符a
cout << pos << endl;
pos = str.find_last_of("123"); //10 匹配最后一个字符3
cout << pos << endl;
pos = str.find_first_not_of("123a",0); // 3 返回在字符串中首次不匹配123a的字符索引
cout << pos << endl;
pos = str.find_last_not_of("389"); //13 返回在字符串中最后一次不匹配389的字符索引
cout << pos << endl;
}