creplacecharacterstrchr

Replacing one character with two in C


I want to replace a character by two characters in my string.

void strqclean(const char *buffer)
{
  char *p = strchr(buffer,'?');
  if (p != NULL)
    *p = '\n';
}

int main(){
    char **quest;
    quest = malloc(10 * (sizeof(char*)));
    quest[0] = strdup("Hello ?");
    strqclean(quest[0]);
    printf(quest[0]);
    return;
}

This works fine, but in fact I want to replace my "?" by "?\n". strcat doesn't works with pointers is that right ? I can find a solution adding a character in my string and replace it by '\n', but that's not what I really want.

Thanks !


Solution

  • EDIT

    In your initial answer you mentioned that you wanted to append a newline after the ?, but now this reference is gone.

    My first answer addressed this, but since it's gone, I'm not sure what you really want.


    NEW ANSWER

    You have to change your strqclean function

    // remove the const from the parameter
    void strqclean(char *buffer)
    {
      char *p = strchr(buffer,'?');
      if (p != NULL)
        *p = '\n';
    }
    

    OLD ANSWER

    strcat works with pointers, but strcat expects C-string and expects that the destination buffer has enough memory.

    strcat allows you to connate strings. You can use than to append the \n if the ? character is always at the end of the string. If the character that you want to replace is in the middle, the you have to insert the character in the middle. For that you can use use memmove that allows you to move chunks for memory when the destination and source overlap.

    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        char line[1024] = "Is this the real life?Is this just fantasy";
        char *pos = strchr(line, '?');
        if(pos)
        {
            puts(pos);
            int len = strlen(pos);
            memmove(pos + 2, pos + 1, len);
            pos[1] = '\n';
        }
        puts(line);
        return 0;
    }