Mike
Mike

Reputation: 109

C - Deleting whitespace inside a string

I'm inputting a string by using fgets, e.g. "Hello World". I want to try and delete the white space inbetween the word, however what I am trying keeps returning hello@world (where @ is a random character).

void sortString(char phrase[])
{
    int i, j;
    char temp[200];


    for(i = 0; i < 200; i++)
    {
        if(!(isspace(phrase[i])))
        {
            temp[i] = phrase[i];
        }
    }

    printf("%s", temp);
}

So i'm basically copying the character[i] over from the phrase to a temp array if it isn't a whitespace, but i'm unsure as to why i'm getting a random character instead of just, for example, helloworld.

Upvotes: 0

Views: 161

Answers (4)

Gandaro
Gandaro

Reputation: 3443

Because you don't assign a value to the string at the positions where whitespace is.

A working code would be:

void sortString(char phrase[])
{
    int i = 0, j;
    char *temp = malloc(strlen(phrase) + 1);

    if (temp == NULL)
    {
        perror("A fatal error occured...\n");
        return;
    }

    for (j = 0; phrase[j]; j++)
    {
        if(!(isspace(phrase[j])))
        {
            temp[i++] = phrase[j];
        }
    }

    temp[i] = 0;

    printf("%s", temp);
    free(temp);
}

Upvotes: 1

Graham Borland
Graham Borland

Reputation: 60681

Whenever you see a whitespace character in phrase, you are simply skipping over the equivalent location in temp, leaving it uninitialized (containing garbage). You need a separate counter to keep track of the current location in the temp array.

Also, you should check for the string in phrase terminating with a \0 character, rather than blindly copying all 200 characters, and make sure the temp string is safely terminated too.

Making sure temp[] is actually big enough for the resulting output is left as a further exercise. (Look in Gandaro's answer for a clue.)

void sortString(char phrase[])
{
    int i, j;
    char temp[200];

    for(i = 0, j = 0; phrase[i] != '\0'; i++)
    {
        if(!(isspace(phrase[i])))
        {
            temp[j++] = phrase[i];
        }
    }

    temp[j] = '\0';
    printf("%s", temp);
}

Upvotes: 5

jmq
jmq

Reputation: 10370

Even though you're skipping temp[i]=phrase[i], you have incremented the position within temp each time you loop. You need a variable for tracking the location within temp that is independent of i.

Upvotes: 0

cnicutar
cnicutar

Reputation: 182619

At least 3 issues:

  • Are you sure the source string will always be 200 characters long ? Shouldn't you be checking for \0 instead ?

  • You need to use a separate index for temp. Now, as you skip characters, you leave uninitialized "holes" in temp.

  • You need to zero-terminate temp

Upvotes: 3

Related Questions