c++中string的几种赋值方法

2022-07-31 10:45:20

在C++中把字符串封装成了一种数据类型string,可以直接声明变量并进行赋值等操作
c++可以赋一个比现有字符更长的字符串而C不可以

#include "stdafx.h"
#include
#include

#include"string" //操作字符串必须包含的头文件

using namespace std;

void main()
{
string s1 = "aaaaa";
string s2("bbbbb");
string s3 = s2; //通过拷贝构造函数,初始化s3
string s4(10, 'a');
string s5 = "hello"+"world";  //错误
cout << "s1:" << s1 << endl;
cout << "s2:" << s2 << endl;
cout << "s3:" << s3 << endl;
cout << "s4:" << s4 << endl;

return ;
}

c++中string的常用操作

s.empty() 若s为空串,则返回true,否则返回false

s.size()		返回s中字符的个数
s[n]			返回s中位置为n的字符
s1+s2			两个字符串连接
s1=s2			用s2替换s1
v1==v2	     	判断是否相等
v1!=v2			判断是否不相等
  • 作者:董国政
  • 原文链接:https://inite.blog.csdn.net/article/details/72625140
    更新时间:2022-07-31 10:45:20