C语言 用C中的单个空格替换多个空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16790227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:29:37  来源:igfitidea点击:

Replace multiple spaces by single space in C

creplacewhitespace

提问by Jaskaran S.P

I want to repace multiple spaces in a string by single space, however my following code doesn't work. What's the logical mistake?

我想用单个空格替换字符串中的多个空格,但是我的以下代码不起作用。什么逻辑错误?

#include<stdio.h>
#include<string.h>
main()
{
char input[100];
int i,j,n,z=0;
scanf("%d",&n);
z=n;
for(i=0;i<n;i++)
scanf("%c",&input[i]);
for(i=0;i<n;i++)
{
    if(input[i]==' ' && (input[i+1]==' ' || input[i-1]==' '))
    {
        --z;
        for(j=i;j<n;j++)
        input[j]=input[j+1];
    }
}
for(i=0;i<z;i++)
    printf("%c",input[i]);
printf("\n");
}

采纳答案by raj raj

The scanfis giving you some problem: it reads the \nyou give after inputting the length n. So, you will miss the last character since forloop exits. The already given answers are good enough. But if you want to follow your own logic, try this:

scanf给您带来了一些问题:它\n在输入长度后读取您提供的内容n。因此,您将错过for循环退出后的最后一个字符。已经给出的答案已经足够好了。但如果你想遵循自己的逻辑,试试这个:

void main()
{
    char input[100];
    int i = 0,j,n = 0;
    while ((input[n] = getchar()) != '\n') {
        n++;
    }
    input[n] = '
void replace_multi_space_with_single_space(char *str)
{
    char *dest = str;  /* Destination to copy to */

    /* While we're not at the end of the string, loop... */
    while (*str != '
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(void) {
    char *pch;
    char sentence[1000];
    char without[1000];

    printf("Sentence: ");
    fgets(sentence,1000, stdin);
    strtok(sentence, "\n"); // remove any newlines
    pch = strtok(sentence, " ");
    while(pch != NULL) {
      strcat(without, pch);
      strcat(without, " 
#include <stdio.h>
#include <stdlib.h>
void remove_blanks(char* s);

int main()
{
    char const s[] = {'1',' ',' ','2',' ',' ','3'};
    remove_blanks(s);
    printf("%s",s);
    return 0;
}

void remove_blanks(char* s){
    int i=0, delta=0, cnt=0;

    for (i=0;s[i];++i){
        if (s[i]==' ') cnt++;
        if (cnt>1){
            delta+=1;
            cnt=0;
        }
        s[i-delta]=s[i];
        if(delta>0) s[i]='
#include <stdio.h>

#define IN 1
#define OUT 0

int main() {
  int c, spaces, state;

  spaces = 0;
  state = OUT;  
  while ((c = getchar()) != EOF) {

      if ( c == ' ') {
           ++spaces;
           state = OUT;
       }
      else if (state == OUT) {
          state = IN;
          spaces = 0;
      }
      if (c == ' ' && spaces > 1 && state == OUT)
          c = 0;            
      putchar(c);
  }
  return 0;
}
'; } }
"); pch = strtok(NULL, " "); } without[strlen(without)-1] = '
#include <stdio.h>

char* uniq_spc(char* str){
    char *from, *to;
    int spc=0;
    to=from=str;
    while(1){
        if(spc && *from == ' ' && to[-1] == ' ')
            ++from;
        else {
            spc = (*from==' ')? 1 : 0;
            *to++ = *from++;
            if(!to[-1])break;
        }
    }
    return str;
}

int main(){
    char input[]= "  abc   de  f  ";

    printf("\"%s\"\n", uniq_spc(input));//output:" abc de f "
    return 0;
}
'; // remove extra whitespace at the end printf("|%s|\n",without); return 0; }
') { /* Loop while the current character is a space, AND the next * character is a space */ while (*str == ' ' && *(str + 1) == ' ') str++; /* Just skip to next character */ /* Copy from the "source" string to the "destination" string, * while advancing to the next character in both */ *dest++ = *str++; } /* Make sure the string is properly terminated */ *dest = '
for(j=i;j<n;j++)
input[j]=input[j+1];
'; }
'; while (i < n) { if(input[i]==' ' && (input[i+1]==' ' || input[i-1]==' ')) { for(j=i;j<n;j++) input[j]=input[j+1]; n--; } else { i++; } } printf("%s\n",input); printf("\n"); }

回答by Some programmer dude

I would do something like this:

我会做这样的事情:

for(j=i;j<z;j++)
input[j]=input[j+1];

Of course, the above function requires you to properly terminate the string, which you currently do not.

当然,上述函数要求您正确终止字符串,而您目前不需要。

What the function above does, is basically copy the string over itself. The exception is when there is a space, when multiple spaces are simply discarded.

上面的函数所做的基本上是将字符串复制到自身上。例外是当有空格时,多个空格被简单地丢弃。

Since the function modifies the source string, it can not be used on string literals.

由于该函数修改源字符串,因此不能用于字符串文字。

回答by Linus

Why make it more complicated than it needs to be? You can use strtokto check for single whitespaces and just ignore those. Then you can use strcatto concatenate the string into a full sentence and then you're done.

为什么让它比需要的更复杂?您可以使用strtok来检查单个空格并忽略它们。然后你可以使用strcat将字符串连接成一个完整的句子,然后你就完成了。

This is how I did it:

我是这样做的:

#include<stdio.h>
#include<string.h>
int main(void)
    {
        char input[1000];
        int i=0;
        gets(input); 
        for(i=0;input[i]!='##代码##';i++)
        {
            if(input[i]!=' ' || input[i+1]!=' ')
                printf("%c",input[i]);
        }
        return 0;
    }

回答by alex440

##代码##

回答by Evgeniy Volkogon

You cant try this simple code:

你不能尝试这个简单的代码:

##代码##

回答by BLUEPIXY

if(input[i]==' ' && (input[i+1]==' ' || input[i-1]==' '))

if(input[i]==' ' && (input[i+1]==' ' || input[i-1]==' '))

case " 1 3" : when i == 0 accses input[i-1] Out-of-Bounds

case " 1 3" : 当 i == 0 accses input[i-1] 越界

scanf("%d",&n);

scanf("%d",&n);

remain newline, (input[0] <-- '\n')

保留换行符,(input[0] <-- '\n')

fix to

固定到

scanf("%d%*c",&n);

scanf("%d%*c",&n);

##代码##

回答by MOHAMED

You have to fix the following for loop. the limit of your for loop should be zand not n

您必须修复以下 for 循环。你的 for 循环的限制应该是z而不是n

##代码##

by

经过

##代码##

BTW: the fist charachter get by your scanf()(which read charachters) is newline (\n). this newline come from the first scanf()of decimal(%d)

顺便说一句:你的scanf()(读取字符)的第一个字符是换行符(\n)。这个换行符来自scanf()小数(%d)的第一个

回答by Arvind M.

##代码##