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號