首页 > 代码库 > C++学习37 string字符串的访问和拼接
C++学习37 string字符串的访问和拼接
访问字符串中的字符
string 字符串也可以像字符串数组一样按照下标来访问其中的每一个字符。string 字符串的起始下标仍是从 0 开始。请看下面的代码:
#include <iostream>#include <string>using namespace std;int main(){ string s1 ; s1 = "1234567890"; for(int i=0, len=s1.length(); i<len; i++) cout<<s1[i]<<" "; cout<<endl; s1[5] = ‘5‘; cout<<s1<<endl; return 0;}
本例中定义了一个 string 变量 s1,并赋值 "1234567890",之后用 for 循环遍历输出每一个字符。借助下标,除了能够访问每个字符,也可以修改每个字符,s1[5] = ‘5‘;
语句就将第6个字符修改为 ’5’,所以 s1 最后为 "1234557890"。
字符串的拼接
有了 string 类,我们可以使用”+“或”+=“运算符来直接拼接字符串,非常方便,再也不需要使用C语言中的 strcat()、strcpy()、malloc() 等函数来拼接字符串了,再也不用担心空间不够会溢出了。
用”+“来拼接字符串时,运算符的两边可以都是 string 字符串,也可以是一个 string 字符串和一个C风格的字符串,还可以是一个 string 字符串和一个 char 字符。请看下面的例子:
#include <iostream>#include <string>using namespace std;int main(){ string s1, s2, s3; s1 = "first"; s2 = "second"; s3 = s1 + s2; cout<< s3 <<endl; s2 += s1; cout<< s2 <<endl; s1 += "third"; cout<< s1 <<endl; s1 += ‘a‘; cout<< s1 <<endl; return 0;}
C++学习37 string字符串的访问和拼接
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。