Search code examples
cwhitespacec-stringsremoving-whitespacefunction-definition

String copy function not copying string properly. What's wrong with my code?


I'm trying to write a function that removes whitesapces from a string and convert it to lower case.

My code below doesn't return anything. Why?

char *removeSpace(char *st);

int main(void){
    char *x = "HeLLO WOrld ";

    x = removeSpace(x);
    printf("output: %s\n", x);

}

char *removeSpace(char *st)
{
    int c = 0;
    char *s = malloc(sizeof(strlen(st)+1));
    for (int x = 0; x < strlen(st); x++)
    {
        if (st[x] != ' ')
        {
            s[x] = tolower(st[x]);
        }
    }
    st= s;

    st= s;
    return st;
}


Solution

  • The malloc statement uses sizeof unnecessarily as mentioned in the comments. You also have an error in the assignment of characters to the new string:

    s[x] = tolower(st[x]);
    

    You use the same index to the new string s as the old string st. This isn't right as soon as you remove any spaces. So for example indexes 0 through 4 line up between the two strings as you copy hello but then you skip a space at index 5 and then you want to assign the w at st[6] to s[5]. This means you need a separate index to track where you are in the destination string. So you need something like this code, which cleans up malloc(), adds the missing header includes, and introduces a new index for the output string:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    char *removeSpace(char *st);
    
    int main(void){
        char *x = "HeLLO WOrld ";
    
        x = removeSpace(x);
        printf("output: %s\n", x);
    
    }
    
    char *removeSpace(char *st)
    {
        size_t len = strlen(st);
        int newStrIdx = 0;
        char *s = malloc(len+1);
        for (int x = 0; x < len; x++)
        {
            if (st[x] != ' ')
            {
                s[newStrIdx++] = tolower(st[x]);
            }
        }
        s[newStrIdx] = '\0';
    
        return s;
    }
    

    Oh, and you forgot the null-terminate the output string, which I added at the end.