C语言删除字符串中除字母外所有字符的程序

要理解这个示例,您应该了解以下 C 编程 主题


除字母外移除字符串中的字符

#include <stdio.h>
int main() {
   char line[150];
   
   printf("Enter a string: ");
   fgets(line, sizeof(line), stdin); // take input


   for (int i = 0, j; line[i] != '\0'; ++i) {

      // enter the loop if the character is not an alphabet
      // and not the null character
      while (!(line[i] >= 'a' && line[i] <= 'z') && !(line[i] >= 'A' && line[i] <= 'Z') && !(line[i] == '\0')) {
         for (j = i; line[j] != '\0'; ++j) {

            // if jth element of line is not an alphabet,
            // assign the value of (j+1)th element to the jth element
            line[j] = line[j + 1];
         }
         line[j] = '\0';
      }
   }
   printf("Output String: ");
   puts(line);
   return 0;
}

输出

Enter a string: p2'r-o@gram84iz./
Output String: programiz

该程序从用户那里获取一个字符串输入,并将其存储在 line 变量中。然后,使用 for 循环遍历字符串中的字符。

如果字符串中的字符不是字母,则将其从字符串中删除,并将剩余字符的位置向左移动 1 位。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战