【问题标题】:removing spaces from a string in C languageC语言从字符串中删除空格
【发布时间】:2019-09-14 19:58:15
【问题描述】:

如果不使用 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;
}

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

示例

输入: " this is my program."

输出: " this is my program."

预期输出: "this is my program."

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

【问题讨论】:

  • 您是否要删除字符串中的所有空格?或者您是否要删除单词之间的所有多余空格?你能提供“这是我的程序”的预期输出吗?输入?
  • 我更新了,想去掉单词之间所有多余的空格,还要去掉句首的空格。

标签: c string token


【解决方案1】:
#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;
}

【讨论】:

    【解决方案2】:

    我也想删除开头的所有空格。

    获得输入后,开始处理直到第一个非空白。

    // do not use gets()
    fgets(text, sizeof text, stdin);
    text[strcspn(text, "\n")] = '\0';  //lop off potential \n
    
    char *ptext = text;
    while (isspace((unsigned char) *ptext)) {
      ptext++;
    } 
    
    // now use ptext instead of text for rest of code.
    

    【讨论】:

    • isspace() 未在问题中提到的任何一个允许的标头中声明。
    【解决方案3】:

    此函数将根据需要处理输入数组

    void remove_white_space(char *source, char *result) {
        int i=0,key=0,k=0;
        while (source[i]!='\0') {
            if(source[i]==' ') {
                if (key== 0) {
                    if(i==0) {
                        key=1;
                        ++i;
                    } else {
                        key=1;
                    result[k]=source[i];
                    ++k;
                    ++i;
                    }
                } else
                    ++i;
            } else {
                key=0;
                result[k]=source[i];
                ++k;
                ++i;
            }
        }
            result[k]='\0';
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-09
      • 2010-12-03
      • 2010-12-16
      • 2011-09-21
      • 2017-11-20
      相关资源
      最近更新 更多