c - 在C中将一个字符串包含到另一个字符串中

标签 c string concatenation strcat

如何在 C 中将一个字符串“包含”到另一个字符串中?

这是一个例子:

string1 = "www.google";
string2 = "http://"+string1+".com";

我在使用 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);
}

略有不同的变体避免了两次格式字符串:

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);
}

关于c - 在C中将一个字符串包含到另一个字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9144106/

相关文章:

c - 编译 GCC Ubuntu : undefined reference to 时出错

string - 如何将 Red/Rebol 字符串转换为系列

字符串格式截断值

list - 如何 append 到 Terraform 中的列表?

Jquery - 选择器,由对象和字符串组成,可以吗?

save - Pascal 中的连接字符串

c - getopt_long 在哪里存储无法识别的选项?

c - strcat 不影响全局字符串

c - 卸载 Windows 驱动程序

c++ - 遍历字符串会导致段错误