【问题标题】:(C Programming) How do I insert string into a character array and then print out all the elements of this array?(C 编程)如何将字符串插入字符数组,然后打印出该数组的所有元素?
【发布时间】:2019-07-19 01:19:14
【问题描述】:

我有这个以字符数组temp 的形式呈现的字符串。我想把这个字符数组插入另一个数组temp_list,然后打印出这个数组的内容。换句话说,将许多字符数组存储在一个数组中。谁能告诉我这是否可行,我怎样才能让它发挥作用?

这是我想要完成的一个例子:

int main()
{
    char temp[5] = "begin";
    char temp_list [10];
    temp_list[0] = temp;

    for (int i = 0; i < strlen(temp_list); i++)
    {
        printf("Labels: %s,", temp_list[i]);
    }
}

当我运行这个程序时,它会打印出乱码。

非常感谢任何形式的指导。谢谢。

编辑:

感谢您的回答。他们都非常有帮助。但我还有一个问题……如果我有多个要插入到temp_list 的字符数组怎么办?多次使用strcpy 似乎不起作用,因为我假设该函数基本上用strcpy 传递的字符串替换了temp_list 的全部内容?

【问题讨论】:

  • 您需要为空字符腾出空间。
  • 您应该启用所有警告并听取它们。 temp_list[0] = temp; 这不是复制字符串的方式。
  • 该代码可以编译吗?你有一个从 char* 到 char 的任务,这不应该。

标签: c arrays string character


【解决方案1】:

关于字符串有很多误解。您的数组temp 需要足够大以存储空终止符,因此在这种情况下它需要至少6 的大小:

char temp[6] = "begin"; // 5 chars plus the null terminator

要复制字符串,请使用strcpy:

char temp_list[10];
strcpy(temp_list, temp);

要打印它,传递temp_list,而不是temp_list[i],你也不需要那个循环:

printf("%s\n", temp_list);

最终的程序可能如下所示:

int main()
{
    char temp[6] = "begin";
    char temp_list[10];
    strcpy(temp_list, temp);
    printf("%s\n", temp_list);
    return 0;
}

【讨论】:

  • 谢谢。但是如果我想插入多个字符数组怎么办?我想,strcpy 将不再是一个选择,对吧?既然函数用一个字符串替换了整个数组?
  • 取决于你想如何插入更多。 strcpy 复制字符串,但在 null 终止符之后不会更改任何内容。您还可以使用memcpy 复制固定数量的字节,strcat 允许您连接字符串。例如,如果在 strcpy(temp_list, temp); 之后你会调用 strcat(temp_list, "Hi!"); 它会打印 beginHi!
  • 我想把它做成 {"hello", "world"} 之类的数组。这在 C 语言中是不可能的吗?
  • 你可以试试:char temp[][10] = {"hello", "world"}; char temp_list[20]; strcpy(temp_list, temp[0]); strcat(temp_list, temp[1]);
  • @Tina 在这种情况下,您可能希望 temp_list 也是一个二维数组,如下所示:char temp_list[2][20]; strcpy(temp_list[0], temp[0]); strcpy(temp_list[1], temp[1]); printf("%s %s\n", temp_list[0], temp_list[1]);
【解决方案2】:

这里有三个问题。首先,temp 不足以容纳字符串“begin”。 C 中的字符串以 null 结尾,所以这个字符串实际上占用了 6 个字节,而不是 5 个。所以让 temp 大到足以容纳这个字符串:

char temp[6] = "begin";

或者更好:

char temp[] = "begin";

数组的大小完全符合字符串的需要。第二个问题在这里:

temp_list[0] = temp;

您将一个数组(实际上是指向数组第一个元素的指针)分配给另一个数组的第一个元素。这是将char * 分配给char 的类型不匹配。即使类型匹配,也不是复制字符串的方式。为此,请使用strcpy 函数:

strcpy(temp_list, temp);

最后,您没有正确打印结果:

for (int i = 0; i < strlen(temp_list); i++)
{
    printf("Labels: %s,", temp_list[i]);
}

%s 格式说明符需要一个指向 char 数组的指针才能打印字符串,但您传递的是单个字符。不匹配的格式说明符调用undefined behavior。

要打印单个字符,请改用%c:

for (int i = 0; i < strlen(temp_list); i++)
{
    printf("Labels: %c,", temp_list[i]);
}

或者您可以摆脱循环并使用 %s 打印整个字符串:

printf("Labels: %s", temp_list);

【讨论】:

  • 还有一件事:他在 printf 中使用了不正确的格式说明符来打印 char。
  • @machine_1 不错。已更新。
猜你喜欢
  • 1970-01-01
  • 2013-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多