用c++代码 删除输入的字符串中的除字母以外的字符
时间: 2023-06-06 17:04:18 浏览: 49
以下是用 C 代码删除输入的字符串中的除字母以外的字符的示例代码:
```c
#include <stdio.h>
#include <ctype.h>
#define MAX_LENGTH 100
int main() {
char str[MAX_LENGTH], newStr[MAX_LENGTH];
int i, j;
printf("请输入字符串:\n");
fgets(str, MAX_LENGTH, stdin);
i = 0;
j = 0;
while (str[i] != '\0') {
if (isalpha(str[i])) {
newStr[j] = str[i];
j++;
}
i++;
}
newStr[j] = '\0';
printf("新的字符串为:%s\n", newStr);
return 0;
}
```
该程序使用了 `isalpha` 函数判断每一个字符是否为字母,如果是字母则保留在新的字符串中,否则跳过。最后输出新的字符串。请注意,该程序没有对输入字符串的长度进行限制,如果输入的字符串长度超过了 `MAX_LENGTH`,可能会导致程序出错。
相关问题
使用循环计算输入字符串中大写字母数量的C++程序
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int count = 0;
printf("请输入一个字符串: ");
fgets(str, 100, stdin);
for (int i = 0; i < strlen(str); i++) {
if (str[i] >= 'A' && str[i] <= 'Z') {
count++;
}
}
printf("字符串中大写字母的数量为 %d\n", count);
return 0;
}
将字符串中的字母两两取出c++代码
以下是将字符串中的字母两两取出的 C++ 代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < str.length() - 1; i += 2) {
cout << str[i] << str[i + 1] << " ";
}
cout << endl;
return 0;
}
```
这段代码中,我们首先定义了一个字符串 `str`,然后使用 for 循环遍历字符串中的字符,每次取出两个字符并输出,直到遍历完整个字符串。输出结果为:
```
ab cd ef gh ij kl mn op qr st uv wx yz
```