string (三):处理对象中的字符

<基于 C++ Primer P81>
关键的问题:一是如何获取字符本身,二是如何改变某个字符的特性。
cctype 头文件中的函数

isalnum(c); isalpha(c); iscntrl(c); isdigit(c); 
isgraph(c); islower(c); isprint(c); ispunct(c); 
isspace(c); // 空白包括:空格、横向制表符、纵向制表符、回车符、换行符、进纸符
isupper(c); isxdigit(c); tolower(c); toupper(c);

1.处理每个字符:基于范围的 for 语句
Case 1:

string s("Hello World!!!");
decltype(s.size()) punct_cnt = 0;
for (auto c : s)
	of (ispunct(c))
		++punct_cnt;
cout << punct_cnt << endl;

Case 2:

string s("Hello World!!!");
for (auto &c : s)  // 改变字符串中的字符时使用引用
	of (ispunct(c))
		c = toupper(c);
cout << s << endl;

2.处理部分字符:使用下标 / 使用迭代器(见 <迭代器> 专题)
类似于数组。
Case 1:

for (decltype(s.size()) index = 0;
	index != s.size() && !isspace(s[index]); ++index)
		s[index] = toupper(s[index]);

Case 2:

// 0-15 的十进制数转换成对应的十六进制数
coust string hexdigits = "0123456789ABCDEF";
string result;
string::size_type n;
while (cin >> n)
	if (n < hexdigits.size())
		result += hexdigits[n];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值