c++primer 第五版3.23节练习

字符串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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值