简体   繁体   English

从c中的字符串中删除空格

[英]removing blanks from a string in c

I know its a question that been asked many times before, but i'm not asking for the solution itself, but to know why my solution isn't working.我知道这是一个以前被问过很多次的问题,但我不是在要求解决方案本身,而是想知道为什么我的解决方案不起作用。

this is my solution:这是我的解决方案:

void delete_blanks(char *string)
{
    while (*string)
    {
        if (*string == ' ')
            *string = '\0';

        *string++;
    }
    puts(string);
}

The program just printing blanks (" ") for every input.该程序只是为每个输入打印空白(“”)。
while running with the debugger, I saw that *string is pointing for '\\0' at the end.在使用调试器运行时,我看到*string指向 '\\0' 。 Is it possible to do it "in-place"?是否可以“就地”进行?

This is the original solution found here:这是在这里找到的原始解决方案:

void RemoveSpaces(char* source)
{
  char* i = source;
  char* j = source;
  while(*j != 0)
  {
    *i = *j++;
    if(*i != ' ')
      i++;
  }
  *i = 0;
}

Here is a good in-place implementation这是一个很好的就地实现

int main(void) {
    char inStr[] = "a cat is on the moon";

    int end = 0;

    for (int i = 0; i < strlen(inStr); i++) {
        if (inStr[i] != ' ') {
            if (i != end) {
                inStr[end] = inStr[i];
            }
            end++;
        }
    }

    inStr[end] = '\0';

    printf("%s\n", inStr);
}

Probably because you are modifying the source, the parameter passed to that function, when it looks for spaces, shortcut the source to '\\0', so you are not printing the correct result.可能是因为您正在修改源,传递给该函数的参数,当它查找空格时,将源快捷方式为'\\0',因此您没有打印正确的结果。 try to use other pointers like the examples you give.尝试使用其他指针,例如您给出的示例。

char a[]="it is a sunny morning";
int j=0;
for( int i=0;i<strlen(a);i++){
    if(a[i]!=' '){
        a[j]=a[i];
        j++;
    }
}
for(int i=j;i<strlen(a);i++){
    a[i]='\0';
}
printf("%s",a);

first group the letters without space then remove the letters that exceeds the space.首先将没有空格的字母分组,然后删除超出空格的字母。

output itisasunnymorning输出 itisasunnymorning

It's unclear what you mean by "removing the blanks".目前还不清楚“删除空白”是什么意思。 If all you want to do is print the string without the spaces, you could reduce you function to this:如果您只想打印不带空格的字符串,您可以将函数简化为:

void delete_blanks(char *string)
{
    while (*string)
    { 
        if (*string != ' ')
             putchar(*string);
        string++;
    }
    putchar('\n');
}

If you want to remove the spaces in the underlying string it becomes a bit more complex as you would have to move characters after a ' ' to fill in the gaps.如果您想删除底层字符串中的空格,它会变得有点复杂,因为您必须在 ' ' 之后移动字符以填充空白。 There is no 'empty character' you can insert to fill the hole in the string, you must move the remaining characters to fill it.没有可以插入的“空字符”来填充字符串中的空洞,您必须移动剩余的字符来填充它。

Basically there a 2 major things wrong with your function.基本上,您的功能有两个主要问题。 You are replacing spaces with string terminating characters, signaling that the string ends here.您正在用字符串终止字符替换空格,表示字符串在此处结束。 This is not what you want to do as there might be characters after the space.这不是您想要做的,因为空格后面可能有字符。 In fact, if you only want to print the string you should not be modifying it at all.事实上,如果你只想打印字符串,你根本不应该修改它。

When you are done iterating over the string, string points to the end of the string.当您完成对字符串的迭代后,字符串指向字符串的末尾。 Essentially passing an empty string to puts() .本质上将一个空字符串传递给puts() You need to pass the original value, before you did a lot of ++ on it, to puts()在对它进行大量 ++ 之前,您需要将原始值传递给puts()

You are also doing *string++ when you should really be doing string++.当你真正应该做 string++ 时,你也在做*string++ string++。 This actually works since it is parsed as *(string++) but is terrible for readability.这实际上有效,因为它被解析为*(string++)但对于可读性来说很糟糕。

If you want to remove the spaces between the words of a string,如果要删除字符串单词之间的空格,
the direct answer as follows:直接回答如下:

// #include <ctype.h>
void RemoveSpaces(char *str) {
    char *strBuff = (char*) malloc(strlen(str) + 1), *p = strBuff;
    while (*str) {
        if (!isspace(*str)) {
            *p = *str;
            p++;
        }
        str++;
    }
    *p = '\0';
    printf("%s\n", strBuff);
    free(strBuff);
}

int main(){
    RemoveSpaces("Thank you for help");
}

The Result:结果:

Also, there is another way and gives the same result as follows:此外,还有另一种方法并给出相同的结果如下:

void RemoveSpaces(char *str) {
    while (*str) {
        if (!isspace(*str)) {
            putchar(*str);
        }
        str++;
    }
    printf("%s\n", str);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM