string不是STL的容器(知道这一点的时候我也很吃惊),但是它与STL容器有着很多相似的操作,不需要担心长度问题,还封装了多种多样的方法,十分好用。
#include <string>
最基本:
string str;
这是声明了一个空字符串
还有其他多种方法:
我写了一个示例,便于理解:
#include<bits/stdc++.h> using namespace std; int main(){ int n,i; char cstr[10]="cstr"; string str1="qwertyui"; string str2(str1); string str3(str1,1); string str4(str1,1,2); string str5(cstr); string str6(cstr,2); string str7(5,‘a‘); string str8("zxcv"); string str9(str1.begin(),str1.end()); cout<<str1<<endl<<str2<<endl<<str3<<endl<<str4<<endl<<str5<<endl<<str6<<endl<<str7<<endl<<str8<<endl<<str9<<endl; str1.~string(); }
运行结果如下:
qwertyui
qwertyui
wertyui
we
cstr
cs
aaaaa
zxcv
qwertyui
网上说了一大堆,我感觉最直接的区别,是如果s有三个字符,传统C的字符串的s[3]是’\0’字符,但是C++的string则是只到s[2]这个字符而已。
具体不同的用法 上图:
可以看到string在赋值、拼接还有比较等方面都更方便。
string s; 1) s.empty(); // s为空串 返回true 2) s.size(); // 返回s中字符个数 类型应为:string::size_type 3) s[n]; // 从0开始相当于下标访问 4) s1+s2; // 把s1和s2连接成新串 返回新串 5) s1=s2; // 把s1替换为s2的副本 6) v1==v2; // 比较,相等返回true 7) `!=, <, <=, >, >=` 惯有操作 任何一个大写字母都小于任意的小写字母
当进行string对象和字符串字面值混合连接操作时,+操作符的左右操作数必须至少有一个是string类型的:
string s1(“hello”); string s3=s1+”world”; //合法操作 string s4=”hello”+”world”; //非法操作:两个字符串字面值相加
也许你需要在string中间的某个位置插入字符串,这时候你可以用insert()函数,这个函数需要你指定一个安插位置的索引,被插入的字符串将放在这个索引的后面。
s.insert(0,”my name”);
s.insert(1,str);
这种形式的insert()函数不支持传入单个字符,这时的单个字符必须写成字符串形式。为了插入单个字符,insert()函数提供了两个对插入单个字符操作的重载函数:
insert(size_type index, size_type num, chart c)和insert(iterator pos, size_type num, chart c)。
其中size_type是无符号整数,iterator是char*,所以,你这么调用insert函数是不行的:
insert(0, 1, ‘j’);这时候第一个参数将转换成哪一个呢?
所以你必须这么写:insert((string::size_type)0, 1, ‘j’)!
第二种形式指出了使用迭代器安插字符的形式。
s.substr(); // 返回s的全部内容 s.substr(11); // 从索引11往后的子串 s.substr(5,6); // 从索引5开始6个字符
int n=1; str1="100"; stringstream stream; stream<<str1; stream>>n; cout<<n<<endl;
参考 :
https://blog.csdn.net/manonghouyiming/article/details/79827040
原文:https://www.cnblogs.com/dyhaohaoxuexi/p/11333009.html