《C++ Primer》5th 课后练习 第三章 字符串、向量和数组 1~10

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_40758751/article/details/102733491

练习3.1 使用恰当的using 声明重做 1.4.1节和2.6.2节的练习。

练习3.2 编写一段程序从标准输入中一次读入一行,然后修改该程序使其一次读入一个词。

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s("");
    while(getline(cin, s))
        if(!s.empty())
            cout << s << endl;
//    while(cin >> s)
//        cout << s << endl;
    return 0;
}

练习3.3 请说明string类的输入运算符和getline函数分别是如何处理空白字符的。

对于string类的输入函数,它会自动忽略开头的空白(空格、制表符、换行等等),从第一个真正的字符开始直到下一个空白。

对于getline()函数,它会保存字符串中的空白符,它读入数据,直到遇到换行符位置。

练习3.4 编写一段程序读取两个字符串,比较其是否相等并输出结果。如果不相等,输出比较大的那个字符串。改写上述程序,比较输入的两个字符串是否等长,如果不等长,输出长度较大的那个字符串。

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s(""), t("");
    cin >> s >> t;
//    if(s == t)
//    {
//        cout << "Thses strings are the same" << endl;
//    }
//    else
//    {
//        cout << (s>t?s:t) << endl;
//    }
    if(s.size() == t.size())
    {
        cout << "The length of these strings are the same" << endl;
    }
    else
    {
        cout << (s.size()>t.size()?s:t) << endl;
    }
    return 0;
}

练习3.5 编写一段程序从标准输入中读入多个字符串并将他们连接起来,输出连接成的大字符串。然后修改上述程序,用空格把输入的多个字符串分割开来。

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s(""), t("");
//    while(cin >> t)
//    {
//        s += t;
//    }
//    cout << s << endl;
    bool flag = 1;
    while(cin >> t)
    {
        if(flag)
        {
            s += t;
            flag = 0;
        }
        else
            s += " " + t;
    }
    cout << s << endl;
    return 0;
}

练习3.6 编写一段程序,使用范围for语句将字符串内所有字符用X代替。

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s("hello world!");
    for(auto &c : s)
    {
        c = 'X';
    }
    cout << s << endl;
    return 0;
}

练习3.7 就上一题完成的程序而言,如果将循环控制的变量设置为char将发生什么?先估计一下结果,然后实际编程进行验证。

如果设为char,则原字符串将不会改变

练习3.8 分别用while循环和传统for循环重写第一题的程序,你觉得哪种形式更好呢?为什么?

我认为用for更好,因为已知循环次数,用while则需要注意更多细节,更容易出错。

练习3.9 下面的程序有何作用?它合法吗?如果不合法?为什么?

string s;
cout << s[0] << endl;

不合法,字符串s默认构造为空字符串,使用下标访问空字符串会造成不可预知的错误。

练习3.10 编写一段程序,读入一个包含标点符号的字符串,将标点符号去除后输出字符串剩余的部分。

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s("h#el$lo w@or^ld!");
    string res;
    for(auto c : s)
    {
        if(!ispunct(c))
            res += c;
    }
    cout << res << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40758751/article/details/102733491
今日推荐