之前做过Java版本的字符串处理,现在对C++当中的字符串进行汇总
C++使用 string 类需要包含头文件,下面的例子介绍了几种定义 string 变量(对象)的方法:
#include字符串长度#include using namespace std; int main(){ string s1; // 未赋值,"",空字符串 string s2 = "c plus plus"; // 初始化并赋值 string s3 = s2; // 直接用s2赋值 string s4 (5, 's'); // 5个s即"sssss" return 0; }
int len = s2.length();查看字符串中字符
cout<替换字符串中字符 s2[5] = 'b'; // "c plus plus" -> "c blus plus"字符串的拼接有了 string 类,我们可以使用+或+=运算符来直接拼接字符串,非常方便
#include#include using namespace std; int main(){ string s1 = "first "; string s2 = "second "; string s = s1 + s2; cout< 字符串的增删改查增可以使用插入insert(size_t pos, const string& str)方法
如果在字符串尾部添加并且添加的是字符(注意只能添加char),则可以用push_back(const char& ch)#include#include using namespace std; int main(){ // 插入 string s1, s2, s3; s1 = s2 = "1234567890"; s3 = "aaa"; s1.insert(5, s3); cout<< s1 < 删一般使用erase(size_t pos = 0, size_t len = npos)
pos 表示要删除的子字符串的起始下标,len 表示要删除子字符串的长度。如果不指明 len 的话,那么直接删除从 pos 到字符串结束处的所有字符(此时 len = str.length - pos)。#include#include using namespace std; int main(){ string s1, s2, s3; s1 = s2 = s3 = "1234567890"; s2.erase(5); s3.erase(5, 3); cout<< s1 < 提取字符串的子串
上边提到查看字符串中单个字符可以直接使用s[pos],当要提取子串时可以使用substr(size_t pos = 0, size_t len = npos)string s1 = "first second third"; string s2; s2 = s1.substr(6, 6); cout<< s1 <查找字符串
size_t find (const string& str, size_t pos = 0) const;
size_t find (const char* s, size_t pos = 0) const;第一个参数为待查找的子字符串,它可以是 string 字符串。第二个参数为开始查找的位置(下标);如果不指明,则从第0个字符开始查找。
string s1 = "first second third"; string s2 = "second"; int index = s1.find(s2,5); if(index < s1.length()) cout<<"Found at index : "<< index <find() 函数最终返回的是子字符串第一次出现在字符串中的起始下标。本例最终是在下标6处找到了 s2 字符串。如果没有查找到子字符串,那么会返回一个无穷大值 4294967295。



