gpt4 book ai didi

c - 如何在 C 中将多个字符串值存储到一个字符串中?

转载 作者:太空宇宙 更新时间:2023-11-04 05:26:49 37 4
gpt4 key购买 nike

我是 C 的新手,所以请原谅我的一些错误。我想知道是否有可能将多个字符串/数组值存储在一个字符串中?这是一个示例,可让您了解我正在尝试做什么。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *lister[] = {"H", "E", "LL", "O"}; //forgot brackets, fixed now

int main()
{
char *mystring[] = ("%s%s", lister[1], lister[2]);
printf ("%s\n", mystring);
return 0;
}

不确定这是否有意义,但正在寻找将字符串值存储到另一个字符串或数组中的方法。谢谢! :) 编辑:strncat 修复了这个问题,如果您遇到同样的问题,请转到 http://www.tutorialspoint.com/c_standard_library/c_function_strncat.htm要了解更多信息,感谢 computerfreaker 建议 strncat!

最佳答案

您缺少一对方括号:

const char *lister[] = {"H", "E", "LL", "O"};
// ^^
// Here

要使用格式字符串将多个字符串合并为一个字符串,您可以使用 sprintf,如下所示:

// Prepare the buffer for the output
char buf[100];
// The format string and parameters come from your code.
sprintf(buf, "%s%s", lister[1], lister[2]);

请注意,您的程序将生成第二个和第三个字符串的值,因为 C 数组中的初始索引为零,而不是一。

关于c - 如何在 C 中将多个字符串值存储到一个字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22404934/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com