【C++】处理string对象中的字符

图片来源:《C++ Primer中文版(第5版)》

特殊函数

#include <cctype>

在这里插入图片描述

统计标点符号

#include <iostream>
#include <cctype>
using namespace std;
int main() {
    string s = "hello!";
    int size=0;
    for(auto c:s)
        if(ispunct(c))
            size++;

    cout<<size;
	return 0;
}

运行结果为1。for(auto c:s)是C++11新标准提供的一种语句:范围for语句。这种语句遍历给定序列的每个元素,并对序列中的每个值执行某种操作,等效于for(int i = 0; i < s.size(); i++)。这是一种非常适合遍历List、Vector、数组、字符串的语句。

ispunct©函数功能:当c是标点符号时为真(即c不是控制字符、数字、字母、可打印空白中的一种)。

将字符串中的小写字母转换为大写

#include <iostream>
#include <cctype>
using namespace std;
int main() {
    string s = "hello!";
    for(auto &c:s)
        c = toupper(c);
    cout<<s;
	return 0;
}

输出结果为:HELLO!

当我们需要改变遍历的元素时,必须把循环变量定义成引用类型。所谓引用只是给定对象的一个别名,因此当我们去改变这个引用,就会改变其绑定的对象。

toupper(c)函数功能:如果c是小写字母,输出对应的大小字母;否则原样输出c。

将首字母转换为大写

#include <iostream>
#include <cctype>
using namespace std;
int main() {
    string s = "hello!";
    if(!s.empty())
        s[0] = toupper(s[0]);
    cout<<s;
	return 0;
}

输出结果:Hello!

将第一个词转换为大写

    string s = "hello word!";
    for(int i=0; i!=s.size() && !isspace(s[i]);i++)
        s[i] = toupper(s[i]);
    cout<<s;
	return 0;

输出结果:HELLO word!

isspace(c)函数:当c是空白时为真(即c是空格、横向制表符、纵向制表符、回车符、换行符、进纸符中的一种)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值