Search code examples
cstringc-strings

How to remove first character from const char* in C language code


Can anyone please help me? I need to remove the first character from a const char * in C.

For example, const char * contents contains a 'x' character as the first character in the array. I need to detect and eliminate this character, modifying the original variable after its been "sanitized".

Can anyone suggest how to achieve it? I'm completely new to C (though I know Java), and just can't seem to figure it out.

Note: I already referred to these, and still not able to figure out: How to remove first character from C-string? - this tell how to remove when the input is char * contents
AND
Difference between char* and const char*? it mentions that const char* is a mutable pointer but points to immutable character/string

What I tried below it works, but why it works?(it should not able to modify the immutable char array contents value "xup")

#include <stdio.h>

int main()
{
    char input[4] = "xup";
    removeLeadingX(input);

    return 0;
}

int removeLeadingX(const char * contents)
{
         //this if condition is something I have to add
         //can't modify other code (ex: the method receives const char * only)
         if(contents[0] == 'x'){
            contents++;
        }
            printf(contents);//up - why immutable string "xup" updated to "up"?
            return 0;

}

Solution

  • You can't remove anything from the const char object.

    1. You need to make a copy of the string and then modify and use the copy
    const char *original = "Hello world!";
    
    char *copy = strdup(original);
    
    copy[strlen(copy) - 1] = 0;  //removing `!`
    
    1. You can modify the pointer to reference other element of the string. But you lose the original pointer and actually do not remove anything from the string.
        const char *original = "Hello world!";
        original = strchr(original, 'w');
        printf("%s\n", original);
    

    What I tried below it works, but why it works?(it should not able to modify the immutable char array contents)

    In your example you modify the pointer not the object referenced by the pointer. It is OK.

    If you declare this function as

    void removeLeadingX(const char * const contents)
    

    the pointer will also be const and your code will not compile.