Append Char To String in C?

前端 未结 9 1060
滥情空心
滥情空心 2020-11-27 16:17

How do I append a single char to a string in C?

i.e

char* str = \"blablabla\";
char c = \'H\';
str_append(str,c); /* blablablaH */
相关标签:
9条回答
  • 2020-11-27 16:35

    The Original poster didn't mean to write:

      char* str = "blablabla";
    

    but

      char str[128] = "blablabla";
    

    Now, adding a single character would seem more efficient than adding a whole string with strcat. Going the strcat way, you could:

      char tmpstr[2];
      tmpstr[0] = c;
      tmpstr[1] = 0;
      strcat (str, tmpstr);
    

    but you can also easily write your own function (as several have done before me):

      void strcat_c (char *str, char c)
      {
        for (;*str;str++); // note the terminating semicolon here. 
        *str++ = c; 
        *str++ = 0;
      }
    
    0 讨论(0)
  • 2020-11-27 16:42

    Easiest way to append two strings:

    char * append(char * string1, char * string2)
    {
        char * result = NULL;
        asprintf(&result, "%s%s", string1, string2);
        return result;
    }
    
    0 讨论(0)
  • 2020-11-27 16:45
    char* str = "blablabla";     
    

    You should not modify this string at all. It resides in implementation defined read only region. Modifying it causes Undefined Behavior.

    You need a char array not a string literal.

    Good Read:
    What is the difference between char a[] = "string"; and char *p = "string";

    0 讨论(0)
提交回复
热议问题