wordpress 搜索小工具seo推广官网
我们知道在C语言里,字符串是以'\0'结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数, 但是这些库函数与字符串是分离开的,而且底层空间需要用户自己管理,可 能还会越界访问。
但是在C++里,却实现了string类,这个string类大大方便了字符串的定义,增添,删除等操作
定义/赋值/增添/合并
int main()
{string s1("hello world");string s2="hello linux"; string s3=s2;string s4;s4=s2;string s5=s1+s2;string ret2 = s1 + "我来了";return 0;
}
迭代器
顺序
假如我们想对字符串进行遍历,那么就需要用迭代器
int main()
{ string s1("hello world");string::iterator it = s1.begin();//begin()函数返回一个迭代器,指向字符串的第一个元素.while (it != s1.end());//end()函数返回一个迭代器,指向字符串的末尾{cout << *it << " ";//打印++it;*it = 'a';//也可以进行修改}cout << endl;return 0;
}
迭代器就类似于一个指针,指向了第一个字母的地址,' * '就是进行解引用
逆序
若是想对字符串进行倒序的读取
string s1("hello world");
auto rit = s1.rbegin();//可以用auto 自动判断类型
while (rit != s1.rend())
{cout << *rit << " ";++rit;
}
cout << endl;
提取字符
//选定字符串,开始的位置,要的字符数
// source_str pos num
string s1("hello world");
string s3(s1, 0, 5);string s5("hello linuxaaaaaaaaaaaaaaaaaaa");
string s6(s5, 6);
//npos(最后一个取的数字不填入)-直接取到最后一个 (npos=-1)string s9(++s8.begin(), --s8.end());//也可以用区间
cout << s9 << endl;
读取长度
string s1("hello world");
//大小
cout << s1.size() << endl;
cout << s1.length() << endl;//容量
cout << s1.capacity() << endl;//clear清理数据
s1.clear();//最大容量
cout << s1.max_size() << endl;
ps:容量capacity不会缩小,只会增大
保存空间/预定空间
string s;
s.reserve(100);//保存100个数据的空间,确定知道大概要多少空间,提前开好,减少扩容,提高效率
改变大小
string s("hello world");
cout << s.size() << endl;
cout << s.capacity() << endl;
cout << s << endl;
//s.resize(13);//默认用'\0'进行改变容量
s.resize(13, 'x');//也可以修改为用'x'进行容量的改变
获取指定位置的字符
s.at(0)++;
s[0]++;
//二者一样,但是at访问失败会返回一个抛异常cout << s2 << endl;
尾插
string ss("world");
string s;
s.push_back('#');//#后加上s的内容
s.append("hello");//在其后边加上这个
cout << s << endl;
s.append(ss);//在s后边加上ss的内容
cout << s << endl;
s += '#';
s += "hello";
s += ss;
cout << s << endl;
粘贴/拷贝
string str;
string base = "dasdasdasdasdasdasdasd";
str.assign(base);//将base的数据拷贝给str,若str已经有数据,那么就会将已有的数据进行覆盖
cout << str << endl;str.assign(base, 5, 10);//resource pos num
cout << str << endl;
查找
string s1("test.cpp");
size_t i = s1.find(".");//找到.的位置,返回下标string s2 = s1.substr(i);//begin..num-num决定了保留的个数,若不输入则默认到结尾
cout << s2 << endl;//如果有多个重复的字符呢?-rfind,返回最后一个出现要找在字符的位置
string s3("test.cpp.tar.zip");
size_t m = s3.rfind('.');
string s4 = s3.substr(m);
cout << s4 << endl;string s5("");
特殊查找
string str("Please, replace the vowels in this sentence by mistakes.");
size_t found = str.find_first_of("aeiou");//找到其中之一的字符即可
//size_t found = str.find("a");
while (found != string::npos)
{str[found] = '*';found = str.find_first_of("aeiou", found + 1);//found = str.find("a", found + 1);
}
cout << str << '\n';
find和find_first_of 区别就是,find是完美匹配要查找的字符串,find_first_of找到其中一个符合的字符即可
除此之外string类里还有很多函数,例如insert erase replace等,可以查,不需要强制记忆,但是上述是比较经常用的,按需记忆。