Musicode Musicode - 2 months ago 24
C Question

Replacing a character in a string (char array) with multiple characters in C

C is not a managed language, and it's been a while since I have used an unmanaged language. I need to create a block of code which searches through a character array, and replaces all instances of '2' with 'Ba'. This is quite simple, except for the fact that now the resulting string will be larger than the original, so I need to account for this somehow, and I don't remember how to do this.

Here is try number 4, using pointers:

//Move next 150 characters after replacing all 2 with Ba:
numberread = read(XYZFile, datatoreadWWW, sizeof(datatoreadWWW));
int y = strlen(datatoreadWWW); //should be 150.
int additionallength = y;
i = 0;
while(i < y) {
if(datatoreadWWW[i] == '2') {
additionallength++; //Since we need to replace any '2' with 'Ba', we should add one character for the a.
}
i++;
}
//And now use additionallength to create the new char array to be placed in WWW, called newstring:
char newstring[additionallength];
int j = 0;
const char *in = datatoreadWWW;
char *out = newstring;
while(*in) {
if (*in == '2') {
*out++ = 'B';
*out++ = 'a';
}
else {
*out++ = *in;
}
in++;
}
*out++ = '\0';


And I'm still confused/stuck on this, I'm getting garbage values written into the WWW file such as "^Q" and such. Not sure what that means, but it doesn't seem correct.

Edit: The program above seems to be working now. The problem was, if anyone ever reads this post as a resource, that I was adding +1 to additionallength, but this was happening in every iteration, so every so many characters there was an extra empty, null space being put in to the file, which was incorrect. Regardless, I think we've learned that is important to review pointers whenever working in C, as this is the easiest way to accomplish this.

Answer

You can do it like this:

  • Compute the length of the new array by adding the number of '2's to strlen of your string plus one for null terminator
  • Allocate the required number of chars using malloc
  • Go through your string in a loop; if you see '2', add 'B' followed by 'a' to the output;
  • Otherwise, copy the current character to the output.

Note: now that your string is allocated dynamically, you need to call free once you are done using it.

const char* str = ...
int cnt = strlen(str)+1;
for (const char *p = str ; *p ; cnt += (*p++ == '2'))
    ;
char *res = malloc(cnt);
char *out = res;
const char *in = str;
while (*in) {
    if (*in == '2') {
        *out++ = 'B';
        *out++ = 'a';
    } else {
        *out++ = *in;
    }
    in++;
}
*out++ = '\0';

Demo.