kyo*_*ori 2 c string concatenation strcat
如何在C中将字符串"包含"到另一个字符串中?
这是一个例子:
string1 = "www.google";
string2 = "http://"+string1+".com";
Run Code Online (Sandbox Code Playgroud)
我在使用strcat()时遇到了困难.
谢谢
snprintf如果有可用空间,您可以使用它的功能返回所需的大小:
const char *string1 = "www.google";
char *string2;
size_t length;
length = snprintf(NULL, 0, "http://%s.com", string1);
if (length < 0) {
// Handle error.
} else {
string2 = malloc(length + 1);
snprintf(string2, length + 1, "http://%s.com", string1);
}
Run Code Online (Sandbox Code Playgroud)
略有不同的变体,避免使用格式字符串两次:
const char *string1 = "www.google";
const char *format = "http://%s.com";
char *string2;
size_t length;
length = snprintf(NULL, 0, format, string1);
if (length < 0) {
// Handle error.
} else {
string2 = malloc(length + 1);
snprintf(string2, length + 1, format, string1);
}
Run Code Online (Sandbox Code Playgroud)