Ad

Remove A Sub-string From A String - C Programming

I am trying to remove all '\x00' hexadecimal values in a particular string.

For example: if the string is "Hello\x00World\x00\x00", I get "Hello" as output, but I need output as "HelloWorld".

Can anyone help me in this?

char *strip(char *str, const char *sub) {
    size_t lenth = strlen(sub);
    if (lenth > 0) {
        char *p = str;
        while ((p = strstr(p, sub)) != NULL) {
            memmove(p, p + lenth, strlen(p + lenth) + 1); // returns a pointer to the destination
        }
    }
    return str;
}
Ad

Answer

A straightforward approach without using standard C string functions can look the following way as it is shown in the demonstrative program below provided that strings contain embedded terminating zero characters '\0' that shall be removed and two consecutive terminating zeroes mean the end of string.

#include <stdio.h>

char * strip( char *s )
{
    char *p = s;
    const char *q = s;
    
    do
    {
        if ( !*q ) ++q;
        
        if ( p != q ) *p = *q;  

        ++p;
    } while ( *q++ );
    
    return s;
}

int main(void) 
{
    char s[] = 
    { 
        'H', 'e', 'l', 'l', 'o', '\x00', 'W', 'o', 'r', 'l', 'd', '\x00', '\x00'
    };
    
    puts( strip( s ) );
    
    return 0;
}

The program output is

HelloWorld

An equivalent initialization of the character array can also look like

char s[] = "Hello\x00World\x00";

Or if to declare the source character array like

char s[] = 
{ 
    '0', '\x00', '1', '\x00', '2', '\x00', '3', '\x00', '4', '\x00', 
    '5', '\x00', '6', '\x00', '7', '\x00', '8', '\x00', '9', '\x00', '\x00'
};

then the program output will be

0123456789
Ad
source: stackoverflow.com
Ad