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;
}

猜你喜欢

转载自blog.csdn.net/weixin_44356804/article/details/109095746