7.4 C++字符串变量的运算 | 使用+输出两个字符串变量

C++字符串变量的运算

在《7.2 C++字符串处理函数》中小林讲过:在以字符数组存放字符串时,字符串的运算要用字符串函数,如strcat strcmp、strcpy。

而对string类对象,可以不用这些函数,直接用简单的运算符。

C++字符串复制

字符串复制可以用赋值号:

string str1,str2;
str1="cyuyan";
str2=str1;

等同于:

strcpy(str1,str2);

C++字符串连接

在C++中可以用+连接两个字符串变量:

string str1="C program"
string str2="language";
string str3;
str3=str1+str2;

C++字符串比较

//可以用关系运算符来进行字符串的比较

== //等于
> //大于
< //小于
!= //不等于
>= //大于等于
<= //小于等于

经典案例:C++使用+连接两个字符变量,并输出连接后的结果。

#include<iostream>//预处理
#include<string> //引入string 
using namespace std;//命名空间 
int main()//主函数 
{
  string str1,str2,str3;//定义字符串变量 
  str1="I love c ";//给字符串变量str1赋初值 
  str2="language";//给字符串变量str2赋初值 
  str3=str1+str2;//给字符串变量str3赋初值 
  cout<<str3;//输出字符串变量的值 
  return 0; //函数返回值为0;
}

执行以上程序会输出:

I love c language
--------------------------------
Process exited after 0.109 seconds with return value 0
请按任意键继续. . .
7.4 C++字符串变量的运算mp.weixin.qq.com图标

文章来源: zhuanlan.zhihu.com,作者:C语言入门到精通,版权归原作者所有,如需转载,请联系作者。

原文链接:zhuanlan.zhihu.com/p/337035036

(完)