c++ Replace character of char pointer with char pointer

546 views Asked by At

I'm having problemes with a function which should replace every character c in the given char array src with the char array text.

first I calculate the length of the return value. Then I insert the correct chars. At least thats what i try.

The problem is I am having unexpected behaviour at the return value. sometimes it replaces only the first matching letter. sometimes is is replacing every an adding one cryptic letter.

char *myreplace(const char *src, char c, const char *text){
    int mylength=0;
    for(int i=0; src[i] != '\0'; i++){
        if(src[i] == c)
            for(int j=0; text[j] != '\0'; j++){
                ++mylength;
            }
        else
            ++mylength;
    }

    char *newtext=new char[mylength+1];

    int x=0;
    for(int i=0; src[i] != '\0'; i++){
        if(src[i] == c)
            for(int j=0; text[j] != '\0'; j++){
                newtext[i+x] = text[j];
                ++x;
            }
        else
            newtext[i+x]=src[i];

    }
    return newtext;
}
1

There are 1 answers

0
1201ProgramAlarm On

When you replace one character with your replacement string, you effectively double increment (both i and x), resulting in skipping one character for each replaced instance and writing past the end of the allocated buffer.

Let's look at an example: src is "abc", text is "d", and ch is 'a'.

When we replace the first character, we write the d to newtext and increment x. The next time thru the loop, we write the second source character ('b') to newtext[i+x], or newtext[2] when it should go to newtext[1].

The simplest fix is to decrement x by 1 after copying in the replacement string.

You're also not writing the terminating nul character '\0' to the end of your newtext string. (Add nexttext[x+i] = 0; before the return.)