字符串string与for语句
#include <iostream>
using namespace std;
int main()
{
string str("Hollo,world !!!");
decltype (str.size()) count = 0; //count 和str.size
的类型一样无符号
for (auto c :str) //对str中的每个字符
if (ispunct(c)) //如果是标点符号
++count;
cout << "共有标点:"<< count << endl;
for (auto &c :str) //必须是引用c
c = toupper(c); // 把c装换为大写
cout << str << endl;
string str2 ("hello world !!!");
//cin >> str2;
for (decltype (str2.size()) index = 0; //等价于int index
= 0
字符串string与for语句
#include
using namespace std;
int main()
{
string str("Hollo,world !!!");
decltype (str.size()) count = 0; //count 和str.size 的类型一样无符号
for (auto c :str) //对str中的每个字符
if (ispunct(c)) //如果是标点符号
++count;
cout << "共有标点:"<< count << endl;
for (auto &c :str) //必须是引用c
c = toupper(c); // 把c装换为大写
cout << str << endl;
string str2 ("hello world !!!");
//cin >> str2;
for (decltype (str2.size()) index = 0; //等价于int index = 0
index != str2.size() && ! isspace(str2[index]); ++index) //空格前面的字符
str2[index] = toupper(str2[index]); //换成大写
cout << str2 << endl;
return 0;
}
toupper() 转换为大写函数,ispunct()判断有没有符号函数
用for语句将字符串替换成X,也可以用传统for语句
include
using namespace std;
int main()
{
string str;
cin >> str;
for (auto &c :str)
c = 'X';
cout << str << endl;
return 0;
}
2.编写一段程序,读入一段含有标点的字符串,将标点去掉在输出剩下的串;
include
using namespace std;
int main()
{
cout << "输入一段含有标点的字符串:\n";
string str;
getline(cin ,str);
for (auto c :str)
if (!ispunct(c))
cout << c ;
cout << "\n";
return 0;
}
用传统方法:
#include
using namespace std;
int main()
{
cout << "输入一段含有标点的字符串:\n";
string str;
getline(cin ,str);
int num = str.size(), i;
for (i = 0; i < num; i++)
{
if (!ispunct(str[i])) //判断是不是标点
cout << str[i];
}
return 0;
}
@Harding 2017-09-24 09:23 字数 阅读 0