您的位置:首页 > 编程语言 > C语言/C++

C++之STL之string

2016-10-16 12:24 363 查看
/*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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: