sheshkovsky
sheshkovsky

Reputation: 1340

How to replace a character in a string with NULL in ANSI C?

I want to replace all 'a' characters from a string in ANSI C. Here's my code:

#include <stdio.h>
#include <stdlib.h>

void sos(char *dst){
    while(*dst){
        if(*dst == 'a')
        *dst = '\0';
        dst++;
        }
}


int main(void){
    char str[20] = "pasternak";
    sos(str);
    printf("str2 = %s \n", str);
    return 0;
}

When I run it, result is:

str2 = p

But it should be

str2 = psternk

It works fine with other characters like 'b' etc. I tried to assign NULL to *dst, but I got error during compile.
How can I remove 'a' characters now?

Upvotes: 1

Views: 4984

Answers (4)

Dan
Dan

Reputation: 4522

'\0' is how the C language tools recognize the end of the string. In order to actually remove a character, you'll need to shift all of the subsequent characters forward.

void sos(char *dst) {
  int offset = 0;
  do {
    while (dst[offset] == 'a') ++offset;
    *dst = dst[offset];
  } while (*dst++);
}

Upvotes: -2

Luiz Vieira
Luiz Vieira

Reputation: 590

The answers previously provided are perfect to explain why your code does not work. But you can try to use strtok to split the string based on the 'a' characters, to then join the parts together or simply print them appart. Check this example: http://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm

Upvotes: 0

xorguy
xorguy

Reputation: 2744

In C, strings are zero-terminated, it means that when there's a '\0' in the string it is the end of the string.

So what you're doing is spliting the string in 3 different ones:

p
stern
k

If you want to delete the a you must move all the characters after the a one position.

Upvotes: 2

What printf does is: read bytes until a '\0' is found.

You transformed "pasternak" to "p\0astern\0k", so printf prints p.

This convention is used on the string functions of the stdlib so that you don't have to pass string length as an argument.

This is why it is said that in C strings are null terminated: it is just a convention followed by the C stdlib.

The downside, as you discovered, is that strings cannot contain \0.

If you really want to print a given number of bytes, use something like fwrite, which counts the number of bytes to be printed, so it can print a \0.

Upvotes: 1

Related Questions