最近做互联网笔试题发现,很多都考察到字符串,而字符串在 C++ 中主要是用 string 来实现的,所以来总结一下
参考 《C++ Primer》320页
string str = "apple banban";
- 遍历
for(int i=0; i < str.size(); i++){
cout<<str[i]<<" ";
}
- 构造 string 的其他方法
string s1(str, 6); // banban
string s2(str, 6, 3); // ban
- substr
string str2 = str.substr(3, 6);
cout<<str2; // le ban
string str3 = str.substr(3);
cout<<str3; // le banban
string str = "apple banban";
- insert
string tt = "orange ";
string s1 = str;
cout<<s1.insert(6, tt); // apple orange banban
cout<<endl;
string s2 = str;
cout<<s2.insert(6, tt, 2, 3); // apple angbanban
- erase
str.erase(3, 3);
cout<<str; // appbanban
str.erase(str.begin() + 3);
cout<<str; // appe banban
str.erase(str.begin() + 3, str.begin() + 6);
cout<<str; // appbanban
- append
str.append(" ttt");
cout<<str; // apple banban ttt
str.append(" abcdef", 0, 3);
cout<<str; // apple banban ab
string str = "apple banban";
- replace
str.replace(3, 6, " 000 ");
cout<<str; // app 000 ban
str.replace(3, 6, " 000 ", 1, 3);
cout<<str; // app000ban
string 的搜索操作
// 搜索操作返回指定字符出现的下标,如果未找到则返回 npos
s.find(args) // 查找 s 中 args 第一次出现的位置
s.rfind(args) // 查找 s 中 args 最后一次出现的位置
s.find_first_of(args) // 在 s 中查找 args 中任何一个字符第一次出现为位置
s.find_last_of(args) // 在 s 中查找 args 中任何一个字符最后一次出现为位置
s.find_first_not_of(args) // 在 s 中查找第一个不在 args 中的字符
s.find_last_not_of(args) // 在 s 中查找最后一个不在 args 中的字符
string str = "apple banban";
如果搜索失败,则返回一个名为 string::npos 的 static 成员。
标准库将 npos 定义为一个 const string::size_type 类型,初始化为 -1
- find 函数完成最简单的搜索。它查找参数指定的字符串,若找到,则返回第一个匹配位置的下标,否则返回 npos
搜索是大小写敏感的
int position = str.find("ban");
if(position != str.npos){
cout<<"position is "<<position; // 6
}
else{
cout << "not found!!! ";
}
string str = "Mississippi";
auto first_pos = str.find("is"); // 1
auto last_pos = str.rfind("is"); // 4
- compare
string str1 = "123";
string str2 = "123";
cout<<str1.compare(str2); //0
string str1 = "abc";
string str2 = "bc";
cout<<str1.compare(str2); // -1
string str1 = "abcd";
string str2 = "abc";
cout<<str1.compare(str2); // 1
数值转换
stoi() // 字符串转int
stof() // 字符串转 float
stol() // 字符串转 long
to_string() // 数值转字符串
网友评论