C++之STL之string

时间:2023-03-09 15:16:24
C++之STL之string

/*C 语言中字符数组一般会采用char str[]来存放,但是显得会比较麻烦,C++在stl中加入
了string类型,对字符串常用的功能进行了封装,操作起来比较方便*/
#include<cstdio>
#include<string>
using namespace std;
int main(){
string str = "hello world";
for (int i = 0; i< str.length(); i++){
printf("%c",str[i]);
}
return 0;
}

输出结果如下:

hello world

通过迭代器进行访问
#include<cstdio>
#include<string>
using namespace std;
int main(){
string str = "hello world";
/*通过迭代器进行访问*/
for (string::iterator it = str.begin(); it != str.end(); it ++){
printf("%c",*it);
}
return 0;
}

/*string的拼接*/
#include<iostream>
#include<string>
using namespace std;
int main(){
string str1 = "hello world", str2 = "form China voice", str3;
str3 = str1 + str2; //将str1和str2拼接,直接赋值给str3
str1 += str2; // 将str2直接拼接到str1上
cout<<str3<<endl;
cout<<str1<<endl;
return 0;
}

输出结果::

hello world

hello world