- 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 . . .
读入一个包含标点符号的字符串,将标点符号去除后输出。
第一种:
#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 . . .

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

被折叠的 条评论
为什么被折叠?



