编写一个 C 语言程序,移除字符串中除字母外的所有字符。for 循环遍历字符串字符,if 语句查找非字母字符。如果条件为真,则跳过该字符,以移除字符串中除字母外的所有字符。
#include <stdio.h>
#include <string.h>
int main()
{
char strAlphas[100];
printf("Enter A String to Remove Non-Alphabets = ");
fgets(strAlphas, sizeof strAlphas, stdin);
int len = strlen(strAlphas);
for (int i = 0; i < len; i++)
{
if (!(strAlphas[i] >= 'a' && strAlphas[i] <= 'z') || (strAlphas[i] >= 'A' && strAlphas[i] <= 'Z'))
{
for (int j = i; j < len; j++)
{
strAlphas[j] = strAlphas[j + 1];
}
len--;
i--;
}
}
printf("The Final String after Sorting Alphabetically = %s\n", strAlphas);
}

在此程序中,我们使用了另一个字符串来复制移除所有字母以外的字符后的结果。
#include <stdio.h>
#include <string.h>
int main()
{
char str[100], strAlphas[100];
int i, j;
char temp;
printf("Enter A String to Remove Non-Alphabets = ");
fgets(str, sizeof str, stdin);
int len = strlen(str) - 1;
for (i = 0, j = 0; i < len; i++)
{
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
{
strAlphas[j] = str[i];
j++;
}
}
strAlphas[j] = '\0';
printf("\nBefore removing Non-Alphabets = %s\n", str);
printf("After removing Non-Alphabets = %s\n", strAlphas);
}
Enter A String to Remove Non-Alphabets = c 123 programs at ???? 12 me
Before removing Non-Alphabets = c 123 programs at ???? 12 me
After removing Non-Alphabets = cprogramsatme
移除字符串中除字母外的所有字符的 示例 使用了 isalpha 方法来查找字母。
#include <stdio.h>
#include <string.h>
#include<ctype.h>
int main()
{
char str[100], strAlphas[100];
int i, j;
char temp;
printf("Enter A String to Remove Non-Alphabets = ");
fgets(str, sizeof str, stdin);
int len = strlen(str) - 1;
for (i = 0, j = 0; i < len; i++)
{
if (isalpha(str[i]))
{
strAlphas[j] = str[i];
j++;
}
}
strAlphas[j] = '\0';
printf("\nBefore removing Non-Alphabets = %s\n", str);
printf("After removing Non-Alphabets = %s\n", strAlphas);
}
Enter A String to Remove Non-Alphabets = hello123how 6789
Before removing Non-Alphabets = hello123how 6789
After removing Non-Alphabets = hellohow