C++ 的字符串类 string

简述:

string 是C++ STL 标准模板库提供的,所以其与C++中的各种输入输出,各种容器等都是兼容适配的,使用起来非常方便。

使用:

#include <iostream>
#include <string>
using namespace std; // 在 std 标准命名空间中
...
int main()
{
	string str1;
	string str2("abcd");
	string str3(6, 'a');	// 6个字符 a 初始化str3对象
	cout << str2 << ", " <<str3 << endl;

	char sz[] = "hello, world!"
	string str4(sz);
	cout << str4 << endl;
	
	// string类还支持默认构造函数和拷贝构造函数:
	string s1;
	string s2 = "hello .";
	
// 赋值(除了使用 = )
	string s3;
	s3.assign("ssss");
	cout << s3 << endl;
	
	char *p = "hello,world!";
	s3.clear();
	s3.assign(p, 5);
	cout << s3 << endl;
	s3.clear();
	s3.assign(p, 7, 5);
	cout << s3 << endl;
	
// 连接
	string s4 = "abc";
	s4 += "def";
	cout << s4 << endl;	// abcdef

	s4.append("s4");
	cout << s4 << endl;

	s4.append(4, 'u');
	cout << s4 << endl;

	s4.append(p, 1, 4);
	cout << s4 << endl;

	// 比较
	string s5 = "241";
	bool ret = (s5 == "123");
	cout << ret << endl;	// 1相等

	if (s5.compare("34") < 0)	// 从头开始比较ascii
	{
		cout << "xiaoyu" << endl;	// xiaoyu
	}
	if (s5.compare(1,2,"23") > 0)	// 从下标为1 的后两字符比较
	{
		cout << "dayu" << endl;	// dayu
	}
	string s6 = "124";	// 123
	if (s6.compare(1,2,"23") == 0)	// 从下标为1 的后两字符比较
	{
		cout << "dengyu" << endl;	// 不输出
	}
	if (s6.compare(2,1,"24",1,1) == 0)	// 从下标为2 的后1个字符比较
	{
		cout << "dengyu" << endl;	// dengyu
	}

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值