c++中的string学习笔记

标准库类型string

使用string需要包含的头文件:

int main() {	
	string s1 = "Hello world  ";//拷贝初始化
	string s2(5, 'M');//直接初始化
	string s_end = s1 + s2 ;
	cout << s_end << endl;
	cout << s1[0] << "----" << s2[0] << endl;
	return 0;
}

Hello world  MMMMM
H----M

#include <iostream>
#include <string>
using namespace std;
int main() {
	string s1;
	while (cin >> s1)
	{
		cout << "s1:" << s1 << endl;
	}
	return 0;
}

string对象会自动忽略开头的空白,即从第一个真正的字符开始读取,直到遇到第二个空白为止

  hello
s1:hello
   hello   world
s1:hello
s1:world

若要使得保持string对象之间的空白,可使用getline()函数:

int main() {
	string s1;
	while (getline(cin,s1))
	{
		cout << "s1:" << s1 << endl;
	}
	return 0;
}
    hello  world  ! ! !
s1:    hello  world  ! ! !  //开头的空白也会保留

empty()与size()函数

int main() {
	string s1;
	while (getline(cin,s1))
	{
		cout << "s1:" << s1 << endl;
		cout << "检测是否为空"   << s1.empty() << endl;
		cout << "string对象的大小  " << s1.size() << endl;
	}
	return 0;
}
 hello world ! ! !
s1: hello world ! ! !
检测是否为空0
string对象的大小  18

循环读取string对象

using namespace std;
string s1 = "999 Hello world ! ! ! 666";
decltype (s1.size()) alpha_cnt = 0, alnum_cnt =0, upper_cnt=0, lower_cnt = 0;
//也可以写为
//string::size_type alpha_cnt = 0, alnum_cnt =0, upper_cnt=0, lower_cnt = 0;
int main() {	
	for (auto c : s1) {
		if (isalpha(c)) {
			++alpha_cnt;
		}
		if (isalnum(c)) {
			++alnum_cnt;
		}
		if (isupper(c)) {
			++upper_cnt;
		}
		if (islower(c)) {
			++lower_cnt;
		}

	}
	cout << "string对象中的字母数量为:" << alpha_cnt << endl;
	cout << "string对象中的字母与数字数量为:" << alnum_cnt << endl;
	cout << "string对象中的大写字母数量为:" << upper_cnt << endl;
	cout << "string对象中的小写字母数量为:" << lower_cnt << endl;
	return 0;
}
string对象中的字母数量为:10
string对象中的数字数量为:16
string对象中的大写字母数量为:1
string对象中的小写字母数量为:9
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值