C++ string初始化、string赋值操作、string拼接操作

以下介绍了string的六种定义方式,还有很多,这个只是简单举例

cpp 复制代码
#include<iostream>

using namespace std;

int main() {
	
	//1 无参构造
	string s1;
	cout << s1 << endl;

	//2 初始化构造
	string s2 ({'h', 'h', 'l', 'l', 'o'});
	cout << s2 << endl;

	//3 字符串初始化
	string s3("xiaoxiao");
	cout << s3 << endl;
	
	//4 字符串的前n个字符
	string s4("xiaoxiaoxiao", 6);
	cout << s4 << endl;
	
	//5 拷贝构造
	string s5(s4);
	cout << s5 << endl;
	

	// a 个 b
	string s6(8, 'o');
	cout << s6 << endl;




    return 0;

}

以下是string的六种赋值操作,以下是代码

cpp 复制代码
#include<iostream>
using namespace std;

int main() {
	//1 字符串常量的赋值
	string s1;
	s1 = "xiaoxiao";
	cout << s1 << endl;

	//2 字符串变量的赋值
	string s2;
	s2 = s1;
	cout << s2 << endl;

	//3 字符常量赋值
	string s3;
	s3 = 'a';
	cout << s3 << endl;

	//4 assign 接口1
	string s4;
	s4.assign("xiaoxiao");
	cout << s4 << endl;

	//5 assign 接口2
	string s5;
	s5.assign("xiaoxiaoxiao", 8);
	cout << s5 << endl;

	//6 assign 接口3
	string s6;
	s6.assign(s5);
	cout << s6 << endl;

	//7 a个b
	string s7;
	s7.assign(8, '6');
	cout << s7 << endl;



}

string拼接操作,代码见下

cpp 复制代码
#include<iostream>

using namespace std;

int main() {
	// 1 + 运算符重载
	string s1 = "dada";
	string s2 = "xiao";

	s1 = s1 + s2;
	cout << s1 << endl;
	
	// 2 += 运算符重载
	string s3 = "dada";
	string s4 = "xiao";

	s4 += "daxiao";
	cout << s4 << endl;

	// 3 append
	string s5 = "abc";
	s5.append("def");
	s5.append("hijklmn", 4); // 取这个的前四个,进行对应字符串的拼接,这个4代表个数
	s5.append("opqrst", 2, 3);// 取从第二个开始,取三个进行拼接
    cout << s5 << endl;
	// 4 push_back
	string s6 = "abb";
	s6.push_back('6');
	cout << s6 << endl;




	return 0;
}
相关推荐
老鼠只爱大米5 分钟前
LeetCode经典算法面试题 #108:将有序数组转换为二叉搜索树(递归分治、迭代法等多种实现方案详解)
算法·leetcode·二叉树·二叉搜索树·平衡树·分治法
csbysj202010 分钟前
《Foundation 开关:深度解析其原理与应用》
开发语言
郭涤生16 分钟前
C++的函数是否可以做到完全覆盖Linux和windows的跨平台
linux·c++·windows
独自破碎E34 分钟前
【前缀和+哈希】LCR_011_连续数组
算法·哈希算法
梦里小白龙40 分钟前
java 通过Minio上传文件
java·开发语言
fqbqrr41 分钟前
2601C++,复制超文本格式
c++
一条大祥脚41 分钟前
26.1.26 扫描线+数论|因子反演+子序列计数|树套树优化最短路
数据结构·算法
m0_5613596744 分钟前
基于C++的机器学习库开发
开发语言·c++·算法
星空露珠1 小时前
速算24点所有题库公式
开发语言·数据库·算法·游戏·lua
2401_832402751 小时前
C++中的类型擦除技术
开发语言·c++·算法