Search code examples
cstringcharc-strings

Replace one character with multiple characters


I need to replace " " (space) with ", " (comma and space). I have function which receive string as char* and after replacing all this characters prints string on screen.

char* PrintComma(char* Text) {
  for (int i = 0; i < strlen(Text); i++) {
    if (Text[i] == ' ') {
        Text[i] = ',';
    }
  }
  return Text;
}

This replaces " " with "," but I need ", ". I'm not allowed to use a second string or array for saving temp data. I can use only this one string.

Example:

Input => "Hello world my name is"
Output => "Hello, world, my, name, is"

Solution

  • This problem seems like a perfect setup for memmove() which is a library function that copies bytes between two strings but handles overlapping memory blocks.

    memmove(
        char_pointer + make_room_at + room_to_make,
        char_pointer + make_room_at,
        init_size - make_room_at + room_to_make
    );
    

    Here is the application using memmove().

    char* PrintComma(char* Text) {
      for (int i = 0; i < strlen(Text); i++) {
        if (Text[i] == ' ') {
          memmove(
              Text + i + 1,
              Text + i,
              strlen(Text) - i + 1
          );
          Text[i++] = ',';
        }
      }
      return Text;
    }