用C++编写自定义函数stringLower()实现将一个字符串中所有大写字母变为小写字母。在主函数中输入一含有大写字母的字符串,调用该函数并输出改变后的字符串。
时间: 2024-05-11 15:19:26 浏览: 81
下面是实现stringLower()函数的C++代码:
```c++
#include <iostream>
#include <string>
using namespace std;
string stringLower(string str) {
int len = str.length();
for (int i = 0; i < len; i++) {
if (str[i] >= 'A' && str[i] <= 'Z') {
str[i] = str[i] - 'A' + 'a';
}
}
return str;
}
int main() {
string s;
cout << "请输入一个含有大写字母的字符串: ";
getline(cin, s);
cout << "转换前的字符串为: " << s << endl;
string lower_s = stringLower(s);
cout << "转换后的字符串为: " << lower_s << endl;
return 0;
}
```
在主函数中,首先输入一个含有大写字母的字符串,然后调用stringLower()函数对该字符串进行转换,并将转换后的字符串输出。需要注意的是,为了处理包含空格的字符串,我们使用了getline()函数来读取输入。
相关问题
编写一个函数,将字符串中的小写字母转换为大写字母,主函数输入字符串并输出结
您好!以下是将字符串中的小写字母转换为大写字母的函数,您可以将其加入到您的程序中:
```c++
#include <iostream>
#include <cstring>
using namespace std;
void toUpper(char *str) {
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] -= 32;
}
}
}
int main() {
char str[100];
cout << "请输入字符串:" << endl;
cin.getline(str, 100);
toUpper(str);
cout << "转换后的字符串为:" << endl;
cout << str << endl;
return 0;
}
```
在该程序中,toUpper() 函数用来将字符串中的小写字母转换为大写字母。该函数的参数为 char 类型的指针,表示要转换的字符串。函数中,我们使用了 for 循环遍历字符串中的每一个字符,判断并转换小写字母。其中,小写字母的 ASCII 码范围为 97-122,大写字母的 ASCII 码范围为 65-90,它们的 ASCII 码差值为 32,因此将小写字母的 ASCII 码减去 32 就可以得到相应的大写字母的 ASCII 码。最后,我们在主函数中读入字符串,调用 toUpper() 函数进行转换,并输出转换后的字符串。
希望能够帮到您!
编写一个函数,将字符串中的小写字母转换为大写字母,主函数输入字符串并输出结果。
以下是一个C++的示例代码:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
void toUpper(char* str) {
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] -= 32; // 将小写字母转换为大写字母
}
}
}
int main() {
char str[100];
cout << "请输入字符串:";
cin.getline(str, 100); // 使用getline获取带空格的字符串
toUpper(str);
cout << "转换后的字符串为:" << str << endl;
return 0;
}
```
首先定义了一个 `toUpper` 函数,该函数接收一个字符数组指针,遍历该字符串并将小写字母转换为大写字母。
然后在主函数中,使用 `cin.getline` 获取带空格的字符串,并调用 `toUpper` 函数将字符串转换为大写字母。最后输出转换后的字符串。
阅读全文
相关推荐















