C语言教程
C语言控制语句
C语言函数
C语言数组
C语言指针
C语言字符串
C语言数学函数
C语言结构
C语言文件处理
C预处理器

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

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

在本例中,您将学习从用户输入的字符串中删除除字母之外的所有字符。
要理解此示例,您应该了解以下C 编程 主题:
C 数组 C 编程字符串 C for 循环 C while 和 do...while 循环

删除字符串中除字母以外的字符

#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 个位置。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4