如何将 char
c 添加到 char* myChar
之前? c
的值为 "A"
,myChar
的值为 "LL"
。如何将 c
添加到 myChar
以生成 "ALL"
?
最佳答案
这应该有效:
#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
if (new_string) {
new_string[0] = c;
strcpy(new_string + 1, str);
}
return new_string;
}
请记住在使用完后 free()
生成的新字符串,否则会发生内存泄漏。
此外,如果您要对同一个字符串执行数百或数千次此操作,那么还有其他方法可以更有效地执行此操作。
关于c - 如何在 C 中将 char 连接到 char*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8569452/