C语言中的字符串处理起来很麻烦,有很多限制。最主要的应该就是长度是固定的而且结尾的'\0'很容易导致错误。而string用起来就很方便。平时也总是用到string,现在感觉用得熟悉一些了,就稍微总结一下常常用到的一些用法。
首先要用string要包含<string>头文件 。至于用法我觉得描述是说不清楚的。直接看下面的代码吧。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string s = "Hello world!"; //初始化
cout << s << endl;
s = "I'm a student."; //改变string的值
cout << s << endl;
s += "And I'm a good student!"; //在string尾部追加内容
cout << s << endl;
/*在string中间插入字符,这个比较麻烦*/
string::iterator it;//定义迭代器变量
it = s.begin(); //指向字符串的对象首字母
s.insert(it, 'Y'); //在s前面插入一个字符Y
cout << s << endl;
/*删除元素,会用到上面定义的迭代器*/
s.erase(it); //删除第一个元素
cout << s << endl;
s.erase(it, it + 4); //删除0~4区间的字符
cout << s << endl;
s = ""; //清空字符串
cout << s << endl;
s = "hello world!";
cout << s.length() << endl; //查看string对象的长度
s.replace(6, 6, "bearox!"); //把从第6个字符开始的连续的6个字符替换成"bearox!"
cout << s << endl;
cout << s.find("bearox") << endl;//查找第一个子串"bearox",找到的话会返回下标值,否则返回一个很奇怪的数字
cout << s.compare("hello bearox!") << endl; //比较字符串大小,相等返回0.否则返回1或者-1(根据两个字符串的大小)
reverse(s.begin(), s.end()); //将指定的段区间元素反向排列,需要包含头文件<algorithm>
return 0;
}