简体   繁体   English

如何在C中将一个char链接为一个char *?

[英]how to concatenate a char to a char* in C?

How can I prepend char c to char* myChar ? 如何将char c char* myCharchar* myChar I have c has a value of "A" , and myChar has a value of "LL" . 我的c值为"A" ,而myChar的值为"LL" How can I prepend c to myChar to make "ALL" ? 如何将c myChar前面以使其成为"ALL"

This should work: 这应该工作:

#include <string.h>    
char * prepend(const char * str, char c)
{
    char * new_string = malloc(strlen(str)+2);  // add 2 to make room for the character we will prepend and the null termination character at the end
    new_string[0] = c;
    strcpy(new_string + 1, str);
    return new_string;
}

Just remember to free() the resulting new string when you are done using it, or else you will have a memory leak. 只需记住在完成使用free()后得到的新字符串,否则会发生内存泄漏。

Also, if you are going to be doing this hundreds or thousands of times to the same string, then there are other ways you can do it that will be much more efficient. 同样,如果您要对同一个字符串执行数百或数千次此操作,那么还有其他方法可以提高效率。

Well, first you need to figure out storage for your new string. 好吧,首先,您需要弄清楚新字符串的存储空间。 If all I know about the source is a char * , I don't know whether it points to a buffer that I can overwrite and/or is long enough, or whether I need to allocate a new buffer. 如果我只知道char * ,那么我不知道它是否指向我可以覆盖和/或足够长的缓冲区,或者是否需要分配新的缓冲区。

To allocate a new buffer, it'd be something like this: 要分配一个新的缓冲区,将是这样的:

char * strprep(char c, const char * myChar)
{
    /* length, +1 for c, +1 for '\0'-terminator */
    char * newString = malloc(strlen(myChar) + 2);

    /* out-of-memory condition rolls downhill */
    if (newString == NULL) return NULL;

    /* populate the new string */
    newString[0] = c;
    strcpy(newString + 1, myChar);
    return newString;
}

To overwrite in place, you'll need to move the characters over to make room for the new start of string: 要进行适当覆盖,您需要将字符移到新的字符串开头以腾出空间:

char * strprep(char c, char * myChar)
{
    int len = strlen(myChar);
    int i;

    /* Move over! */
    for (i = len; i >= 0; i--) myChar[i + 1] = myChar[i];

    /* Now plug in the new prefix. */
    myChar[0] = c;
    return c;
}

If your C library has it available, you can use memmove in place of the loop to shift the original characters up by one. 如果您的C库可用,则可以使用memmove代替循环将原始字符上移一个。

Probably not the most efficient but this is a step in the right direction: this one is clearly direct approach - 可能不是最有效的方法,但这是朝正确方向迈出的一步:这显然是直接的方法-

  int main()
   {
      int i;
      char tempc;
      for (i=0; i<strlen(str); i++)
      {
        tempc = c;
        c = str[i];
        str[i] = tempc;            
         str[i+1] = c;
      }
       *(str[i+1]) = malloc(1);
       str[i+1] = '\0';
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM