简体   繁体   中英

how to remove space in a string in C?

I'm trying the code below but get a wrong output. For example I type "abc" and I want the result to be "abc", but the result is a chinese character.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
/* function prototype */
char *sweepSpace(char *sentence);
int main()
{
    char str[80];
    printf("Enter a string: ");//enter a string for example "a b c'
    gets(str);
    printf("Result: %s  ", sweepSpace(str));//should print "abc"here 
    return 0;
}
char *sweepSpace(char *setence)
{
    char b[80];     
    int i = 0;
    while (*setence != NULL)
    {
        //if not reach the end
        if (!isspace(*setence))
        {
            //if not a space
            b[i] = *setence;//assign setence to b
            i++;//increment 
        }
        setence++;//pointer increment
    }
    b[i]= "\0";

    return b;//return b to print
}

You are returning a local array variable ( b ), which invokes undefined behavior when it's accessed in main() .

Don't do this.

Copy the new string back before the function ends:

strcpy(setence, b);

Some more notes:

  1. It's spelled sentence .
  2. Check against '\\0' , not NULL .
  3. Cast to unsigned int when using isspace() .
  4. The terminator is '\\0' , not "\\0" .

b is scoped in function. Copy back the result to your original pointer.

Something like:

strcpy(setence, b);

With this code you are trying to return b , which is defined on stack . Once you are out of scope it will not reflect in main .

char b[80];
..
..
return b;//return b to print

Instead, you return new_b .

char* new_b = (char*)malloc(strlen(b)+1);
strncpy(new_b,b,strlen(b)+1);
return new_b;//return b to print

You can't return an automatic array in C . When the function sweepSpace returns, the array b goes out of scope (it's allocated on the stack) and you return the address of a memory location to main which is no longer available. This would cause undefined behaviour and likely result in segfault. Also, never use gets . It does not check the bound of the buffer it writes into and can overrun the buffer if the input string is too large. Use fgets instead. This would again lead to error. Here's what I suggest.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <ctype.h>        // for prototype of isspace
#include <stdlib.h>       // for prototype of malloc

char *sweepSpace(char *sentence);

int main(void)     // parameter list should contain void explicitly
{
    char str[80];  
    printf("Enter a string: "); //enter a string for example "a b c'
    fgets(str, 80, stdin);  // read at most 79 chars. add null byte at the end
    char *new_sentence = sweepSpace(str);
    if(new_sentence) {
        printf("Result: %s  ", new_sentence); //should print "abc" here
        free(new_sentence);
        new_sentence = NULL;
    }
    return 0;
}

char *sweepSpace(char *sentence)
{
    char *b = malloc(1 + strlen(sentence)); // +1 for the null byte
    if(b == NULL) {
        printf("Not enough memory");
        return NULL;
    }     
    int i = 0;
    while(*sentence != '\0')  // compare with null byte, not NULL pointer  
    {
        //if not reach the end
        if (!isspace(*sentence))
        {
            // if not a space

            b[i] = *sentence; //assign sentence to b
            i++;  //increment 
        }
        sentence++; //pointer increment
    }
    b[i]= '\0';   // "\0" is a string literal, not a character.
    return b;  //return b to print
}
char *a="hello world";
int i;
int w=strlen(a);
for(i=0; i<=w; i++) {
if(*(a+i)==' ') { 
for(j=i;j<=w-1;j++) {
*(a+i)=*(a+1);
} }
}

/* if there is a space, push all next character one byte back */

this should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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