c - C语言中去除字符串中的空格

标签 c string token

我不知道如何在不使用 stdio.h 和 stdlib.h 之外的任何库的情况下删除句子开头的空格。

#include <stdio.h>

int main()
{
   char text[1000], result[1000];
   int c = 0, d = 0;

   printf("Enter some text\n");
   gets(text);

   while (text[c] != '\0') { // till the end of the string
      if (text[c] == ' ') {  
         int temp = c + 1;   
         if (text[temp] != '\0') {  
            while (text[temp] == ' ' && text[temp] != '\0') { 
               if (text[temp] == ' ') { 
                  c++;                  
               }  
               temp++;                  
            }
         }
      }
      result[d] = text[c];
      c++;               
      d++;
   }
   result[d] = '\0';

   printf("Text after removing blanks\n%s\n", result);

   return 0;
}

这段代码删除了句子中所有多余的空格。

示例:

输入: “这是我的程序。”

输出: “这是我的程序。”

预期输出: “这是我的程序。”

这段代码只留下一个空格,其中有更多空格,但我想删除开头的所有空格,就像预期的输出一样。

最佳答案

#include <stdio.h>

int main()
{
   char text[1000], result[1000];
   int c = 0, d = 0;

   printf("Enter some text\n");
   gets(text);

   // no space at beginning
   while(text[c] ==' ') { c++; }
   while(text[c] != '\0'){
    result[d++] = text[c++]; //take non-space characters
    if(text[c]==' ') { result[d++] = text[c++]; } // take one space between words
    while(text[c]==' ') { c++; } // skip other spaces 
   }
   result[d] = '\0';

   printf("Text after removing blanks\n%s\n", result);

   return 0;
}

关于c - C语言中去除字符串中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57938824/

相关文章:

html - 如何在单个 csh/perl/python 脚本中将 20 个 .html 文件从 Linux 传输到 Windows?

c - 有什么办法可以加快打印阵列的速度吗?

java - Split 方法是将字符串拆分为单个字符串

Java charAt 意外类型错误

rust - 如何在 `quote!` 宏中的变量之后立即连接 token ?

c - Linux block 系统调用

c - 在C中手动将4位int(十进制)提取到字符串中

java - 字符串(日期)到日期

c++ - 使用 switch case 代替 if else

c - 有没有办法在 C 中计算 token ?