输入一个字符串,把其中的字母字符大小写转换一下,同时把非字母字符单独存放在一个新的字符数组最后以字符串的方式输出(如:输入 a2bN4Pc8defWWg5, 输出 A2Bn4pC8DEFwwG5 和 2484 )。
参考代码:
#include <stdio.h>
#include <ctype.h> // 包含 toupper() 和 tolower() 函数
int main() {
char str[100], letters[100], others[100];
int i, j = 0, k = 0;
printf("请输入一个字符串:\n");
gets(str); // 输入字符串,注意 gets() 函数已经不安全,建议使用 fgets()
for (i = 0; str[i] != '\0'; i++) { // 遍历字符串
if (isalpha(str[i])) { // 如果是字母字符
if (isupper(str[i])) { // 如果是大写字母
str[i] = tolower(str[i]); // 转换为小写字母
} else { // 如果是小写字母
str[i] = toupper(str[i]); // 转换为大写字母
}
letters[j++] = str[i]; // 将转换后的字母字符存入 letters 数组中
} else { // 如果是非字母字符
others[k++] = str[i]; // 将非字母字符存入 others 数组中
}
}
letters[j] = '\0'; // 字母字符数组结尾加上字符串结束符
others[k] = '\0'; // 非字母字符数组结尾加上字符串结束符
printf("转换后的字符串为:%s\n", str); // 输出转换后的字符串
printf("非字母字符为:%s\n", others); // 输出非字母字符数组
return 0;
}
#include <string>
#include <algorithm>
int main() {
std::string str = "a2bN4Pc8defWWg5";
std::string letters;
std::string digits;
for (char c : str) {
if (isalpha(c)) {
letters += std::toupper(c);
} else {
digits += c;
}
}
std::cout << letters << " " << digits << "\n";
}