1.string.find() 正向查找,下标从0开始计算。
返回值是字母在母串中的下标位置。
如果没有找到,那么会返回一个特别的标记npos,一般写作string::npos。
string s, c;
int main() {
s = "apple";
c = "l";
int index = s.find(c);
if (index != string::npos)
cout << index << endl;
}
输出:3
1.1 string.find(str,pos)
从pos开始(包括pos处字符)匹配str的位置。
string s, c;
int main() {
s = "laaaal";
c = "l";
int index = s.find(c,3);//从字符串s下标3的位置开始寻找
if (index != string::npos)
cout << index << endl;
}
输出:5
1.2 string.find_first_of(str) 和 string.find_last_of(str)
目标字符在字符串中第一次出现和最后一次出现的位置。
string s, c;
int main() {
s = "laaaal";
c = "l";
cout << "first index:" << s.find_first_of(c) << endl;
cout << "last index:" << s.find_last_of(c) << endl;
}
输出:
first index:0
last index:5
2.string.rfind() 反向查找
从字符串右侧开始匹配str,并返回在字符串中的下标位置;
string s = "apple";
cout << s.rfind("l") << endl;
输出:3
2.1 string.rfind(str,pos): 从pos开始,向前查找符合条件的字符串;
1.对于字符串"zrftp154:ACkRqhx7",分别取出zrftp154和ACkRqhx7。
#include <iostream>
#include <string>
int main() {
std::string str = "zrftp154:ACkRqhx7";
size_t pos = str.find(":");
if (pos != std::string::npos) {
std::string username = str.substr(0, pos);
std::string password = str.substr(pos + 1);
std::cout << "Username: " << username << std::endl;
std::cout << "Password: " << password << std::endl;
} else {
std::cout << "Invalid format!" << std::endl;
}
return 0;
}
浙公网安备 33010602011771号