C++Primer3.2 标准类型string

初始化string对象

//string的初始化
void test01()
{                                      
	string s1;					// 默认初始化,s1是一个空字符串
	string s2 = s1;				// s2是s1副本
	string s3 = "hiya";			// s3是"hiya"
	string s4(10,'c');			// s4内容是cccccccccc
	string s5;
	cin >> s5;
	cout << s5 << endl;
	cin >> s1 >> s2;
	cout << s1 << s2 << endl;
}

输出:

aa
aa
bb
cc
bbcc
  • 默认初始化,s1是一个空字符串,该string对象没有任何字符
  • string s3 = "hiya"使用 = 初始化一个变量,实际上执行的是拷贝初始化,编译器把等号右边的拷贝到左边的对象中去

读写string对象

读取操作时,string会自动忽略开头的空白(即空格符、换行符、制表符等),然后从第一个真正字符开始读起,直到下一处空白为止。因此,如果输入是" Hello World ",那么输出将是”Hello“,不允许有空格

同时,也可以多个输入多个输出连写在一起

string s1,s2;
cin >> s1 >> s2;
cout << s1 << s2 << endl;

如果上述输入是" Hello World ",那么输出将是”HelloWorld “,也不允许有空格

string的empty和size操作

  • empty函数根据string对象是否为空返回一个对应的布尔值

  • size函数返回string对象的长度(即string对象中字符的个数)

    void test03()
    {
    	string line = "aaa";
    	// .size()得到的是无符号型,与-1比时,无符号转为非常大的有符号型
    	if(line.size() < -1)
    	{
    		cout << "warning" << endl;
    	}
    }
    

    输出:

    warning
    

    由于line.size()会返回一个无符号整型数,所以在表达式line.size()<n,如果在表达式中混用了有符号和无符号数(如line.size() < -1),将会产生报错。因为-1是一个整型负数,在表达式中会自动转换成一个比较大的无符号值。

不同string对象的比较

判断大小的标准:

  1. string长度不同,则较短的string对象 < 较长的string对象
  2. string长度相同,则比较第一个不同符号的字符
void test04()
{
	string s1 = "hello";
	string s2 = "hallo";
	if(s2 < s1)
	{
		string s3 = s1 +","+ s2 + "\n";
		cout << s3 << endl;
	}
}

输出:

hello,hallo

string的加法

string s1 = "hello", s2 = "world";
string s3 = s1 + s2;	// s3内容是helloworld

因为标准库允许把字符‘a’、字符串”a“转换为string对象,因此‘a’、”b“也可以参与到string对象的加法运算中:

string s1 = "hello", s2 = "world";
string s3 = s1 +"," + s2 + '\n';

值得注意得是,如果string对象、‘a’、“b”在同一条语句中使用,必须要保证+号两侧至少有一个string对象.

✅正确:

string s4 = s1 + ",";
string s5 = s1 + "," + "world";

❌错误:

string s6 = "hello" + ",";
string s7 = "hello" + "," + s1;
  • 其中,string s5 = s1 + "," + "world"等价为string s5 = (s1 + ",") + "world"s1 + ","是一个新的string对象
  • string s7 = "hello" + "," + s1等价为string s7 = ("hello" + ",") + s1,而"hello" + ","不是string类型,不能相加

string、“aabb”相似,但不是同一个东西

处理string对象的字符

可以引用cctype库处理string中的字符

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

void test05()
{
	string s = "1d3g135";
	for(int i = 0;i<s.size();i++)
	{
		//判断字符是不是字母
		if(isalpha(s[i]))
		{
			cout << "isalpha" << endl;
		}
	}
}

int main() {
	test05();
	system("pause");
	return 0;
}

image-20240418174434632

遍历string中的每个字符

最简单的就是使用for循环遍历:

for(int i = 0;i<s.size();i++)
{
	cout << s[i] << endl;
}

也可以使用范围for语句,效果一样:

for(auto c : s)
{
	cout << c <<endl;	// c = s[i]
}
  • 22
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落叶随峰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值