2025年4月26日 星期六 乙巳(蛇)年 正月廿七 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > VC/VC++

C++ string字符串的访问和拼接

时间:01-10来源:作者:点击数:115

访问字符串中的字符

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;
  • }

运行结果:

1 2 3 4 5 6 7 8 9 0
1234557890

本例中定义了一个 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;
  • }

运行结果:

firstsecond
secondfirst
firstthird
firstthirda
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门