3.2.3 处理string对象中的字符

在这里插入图片描述
练习3.6

#include <iostream>
using namespace std;
#include <string>

int main() {
    char a = 'X';
    string s;
    getline(cin,s);
    for (auto& c : s) //对于s中的每个字符(注意:c是引用)
        c = a;
    cout << s;
    return 0;
}

字符串里面的所有字符是包含空格的。因此空格的地方也为X
在这里插入图片描述
练习3.7
将auto更改为char,结果一样,说明string里面的每个字符领出来,类型为char类型。

#include <iostream>
using namespace std;
#include <string>

int main() {

    char a = 'X';
    string s;
    getline(cin,s);
    for (char & c : s) //对于s中的每个字符(注意:c是引用)
        c = a;
    cout << s;
    return 0;
}

在这里插入图片描述
练习3.8
for循环语句

#include <iostream>
using namespace std;
#include <string>

int main() {
    string s;
    getline(cin, s);
    for (decltype(s.size())index = 0;
        index != s.size(); ++index)
        s[index] = 'X';
    cout << s;
    return 0;
}

在这里插入图片描述
while循环语句

#include <iostream>
using namespace std;
#include <string>

int main() {
    string s;
    getline(cin, s);
    decltype(s.size())index = 0;
    while (index != s.size()) {
        s[index] = 'X';
        index = index + 1;
    }
    cout << s;
    return 0;
}

在这里插入图片描述
范围for语句更加简洁,自动循环所有字符,不用考虑终止条件。

练习3.9
程序可以运行,s是一个空字符串,s[0]的结果是未定义的,不要这样做。这种错误不会被编译器发现,而是在运行时产生一个不可预知的值。

练习3.10

#include <iostream>
using namespace std;
#include <string>

int main() {
    string s;
    getline(cin, s);
    for (auto& c : s) //对于s中的每个字符
        if (ispunct(c))  //如果该字符是标点符号
            c = ' ';
    cout << s;
    return 0;
}

在这里插入图片描述在这里插入图片描述
上面的代码是将标点符号变成了空格,并没有删除,下面的代码可以实现删除标点符号。

#include <iostream>
using namespace std;
#include <string>

int main() {
    string s; 
    getline(cin, s); 
    string result;
    for (auto& c : s)
        if (!ispunct(c))
            result += c;
    cout << result;
    return 0;
}

在这里插入图片描述

练习3.11
合法,系统没报错,c的类型除了用auto之外,只能是const char,因为s是constant string。不然系统报错

#include <iostream>
using namespace std;
#include <string>

int main() {

    
    const string s = "Keep out!";
    for (const char & c : s) {
        /*...*/
    }
    
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值