C++学习笔记-String对象的操作

这篇博客详细介绍了C++中String对象的操作,包括初始化、使用迭代器和专用方法进行修改,重点讲解了substr、append、replace函数的用法,以及String类型的查找和比较规则,特别是如何根据ASCII码进行字符串比较。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. String对象初始化
string初始化方法 解释
sting s; 创建空的字符串;
string s = “value”; 用值value来初始化字符串s;
string s(“value”); 用值value来初始化字符串s;
string s(s2); 用字符串s2来初始化字符串s;
string s(s2, pos); 从s2的位置pos处开始到最后的所有字符来初始化s;
string s(n, ‘c’); 用n个字符c来初始化s;
string s(b, e); 用迭代器b到e之间的内容初始化字符串s;
string s(chs, n); 用从字符数组chs的前n个字符来初始化s;
string s(s2, pos, len); 从s2的第pos个位置开始的len个字符初始化s;
#include<iostream>
#include<string>

int main()
{
	std::string s1;
	std::string s2 = "Come on, boy!";
	std::string s3("Hello World, Welcome to C++!");
	std::string s4(s3);
	std::string s5(5, 's'); // sssss
	std::string s6(s3.begin() + 6, s3.begin()+6+5); // World
	std::string s7(s3, 6); // World, Welcome to C++!
	
	char *chs = "Project Main."; // 字符指针表示字符串,该字符串的最后有一个'\0'
	char ch2[] = "C plus plus!"; // 字符数组表示字符串,最后有一个'\0';
	char ch3[] = { 'H', 'W' }; // 字符数组,后面没有'\0',因此不算是字符串;
	
	std::string s8(chs, 7); // Project // 从chs开始的前面7个字符
	std::string s9(ch2, 6); // C plus
	std::string s10(ch2 + 7, 5); // plus! // 从chs第7个字符开始的后面5个字符
	std::string s11(ch2); // C plus plus!

	//std::string s11(ch3); // 报错,ch3后面没有'\0';
	std::string s12(ch3, 2); // HW
	std::string s13(chs, 8, 5); // Main. // 从chs的第8个位置开始的5个字符, plus!
	std::string s14(chs, 8, 10); // Main. // 从chs的第8个位置开始的10个字符, 不够10个就取到chs的最后.

	std::cout << s1 << std::endl;
	std::cout << s2 << std::endl;
	std::cout << s3 << std::endl;
	std::cout << s4 << std::endl;
	std::cout << s5 << std::endl;
	std::cout << s6 << std::endl;
	std::cout << s7 << std::endl;
	std::cout << s8 << std::endl;
	std::cout << s9 << std::endl;
	std::cout << s10 << std::endl;
	std::cout << s11 << std::endl;
	std::cout << s12 << std::endl;
	std::cout << s13 << std::endl;
	std::cout << s14 << std::endl;

	//system("pause");
	return 0;
}
2. 修改String对象:

1.通用迭代器方法修改string对象

String对象修改方法 解释
s.insert(p, t); 在迭代器 p 前面插入字符 t;
s.insert(p, n, t); 在迭代器 p 前面插入 n 个字符 t;
s.insert(p, b, e); 在迭代器 p 的位置插入迭代器 b 到 e 直接的所有元素;
s.assign(b
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值