编写一个函数,判断 string 对象中是否含有大写字母。编写另-个函数,把 string 对象全都改成小写形式。在这两个函数中你使用的形参类型相同吗?为什么?

发布时间 2023-07-16 12:50:46作者: wshidaboss

第一个函数的任务是判断 string 对象中是否含有大写字母,无须修改参数的内容,因此将其设为常量引用类型。第二个函数需要修改参数的内容,所以应该将其设定为非常量引用类型。满足题意的程序如下所示:

#include <iostream>
#include <Windows.h>
using namespace std;
bool hasUpper(const string& str) { //判断字符串中是否含有大写字母
    for (auto c:str) {
        if (isupper(c)) {
            return true;
        }
    }
    return false;
}
void ChangeToLower(string& str) { //把字符串中的大写字母转换为小写字母
    for (auto& c : str) {
        c = tolower(c);
    }
}
int main() {
    string str;
    cout << "请输入一个字符串:" << endl;
    cin >> str;
    if (hasUpper(str)) {
        ChangeToLower(str);
        cout << "转换后的字符串为:" << str << endl;
    }
    else {
        cout << "字符串中无大写字母,无需转换!" << endl;
    }
}