C++_auto

本文介绍了两种使用C++处理字符串的方法:一种是遍历字符串并将所有字符替换为‘X’;另一种是移除字符串中的所有标点符号。通过示例展示了如何使用范围for循环和ispunct函数。
  1. 1.
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char const *argv[])
{
    string line;
    getline(cin,line);

    for(auto &c:line)
        c='X';

    cout<<line;

    cout<<line<<endl;
    return 0;
}

这里的for语句为C++11新定义的范围for语句。
注意:
1. 利用auto关键字推断字符串中每一个元素的类型;
2. c必须定义为引用类型,否则无法修改字符串的内容。
这里将字符串line中的所有字符变为‘X’,输出结果为:

What is your name?
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

--------------------------------
Process exited with return value 0
Press any key to continue . . .
  1. 读入一个包含标点符号的字符串,将标点符号去除后输出。

第一种:

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char const *argv[])
{
    string line;
    getline(cin,line);


    for(auto &c:line)
    {
        if(!ispunct(c))
            cout<<c;
    }

    cout<<endl;
    return 0;
}

这里的ispunct(char ch)函数,如果参数ch是除字母,数字和空格外可打印字符,函数返回非零值,否则返回零值。
这里的punct为punctuation(标点符号)的缩写。
由此想到另一个函数,isspace(char ch),若判断字符ch为空格、制表符或换行符,函数返回非零值,否则返回零值。

what,is.your?name!
whatisyourname

--------------------------------
Process exited with return value 0
Press any key to continue . . .

第二种:

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char const *argv[])
{
    string line,result="";
    getline(cin,line);

    for(decltype(line.size()) i=0;i<line.size();i++)
    {
        if(!ispunct(line[i]))
            result+=line[i];
    }

    cout<<result<<endl;
    return 0;
}

decltype 类型说明符生成指定表达式的类型。在此过程中,编译器分析表达式并得到它的类型,却不实际计算表达式的值。
详细用法见:
http://blog.youkuaiyun.com/yhl_leo/article/details/50865552

输出结果:

what,is.your?name!!
whatisyourname

--------------------------------
Process exited with return value 0
Press any key to continue . . .
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值