【问题标题】:Convert a char * [] to a string in C将 char * [] 转换为 C 中的字符串
【发布时间】:2015-02-24 00:40:27
【问题描述】:

如何在 C 语言中将字符指针数组(即字符串数组)转换为单个字符串?

例如:

char * args[MAXLINE/2+1];
char s[MAXLINE] = args; //<-- Pseudo code: How is this accomplished?

它必须涉及从 args 中的每个索引中获取每个字符串并将它们连接在一起以获得最终字符串。但是当我尝试这样做时,我无法让 strcat 使用 char* 数组。

【问题讨论】:

  • strcat 是一种可能的答案,所以我不确定为什么它不适合你。你尝试了什么?
  • 你能给我们你尝试使用strcat的代码吗?
  • 在声明 char *args[MAXLINE/2 + 1] 的地方,它应该类似于 char *args[NUM_STRINGS],因为你声明的是一个字符串数组。该数字与MAXLINE无关,它是组合字符串中的字符数。

标签: c arrays string


【解决方案1】:

您需要遍历指针并将它们连接起来。您还需要非常小心不要溢出目标缓冲区。

不做边界检查的简单实现看起来像这样:

char *ptr = s; // set ptr to the start of the destination buffer
for (i=0; i<number_of_pointers; i++) {
    char *current_arg = args[i];
    char c;
    while ( (c = *current_arg++) ) {
        // copy each character to the destination buffer until the end of the current string
        *ptr++ = c; 
    }
    *ptr++ = ' '; // or whatever joining character you want
}
*ptr = '\0'; // null terminate

您也可以循环调用strcat,但很快就会遇到Schlemiel the Painter

【讨论】:

  • 更新。从 2019 年开始:stpcpy 已添加到 POSIX 标准中,也许 C 也已添加...这使得循环调用更快。
猜你喜欢
  • 2018-03-27
  • 2013-05-13
  • 2012-01-16
  • 2018-09-02
  • 1970-01-01
  • 1970-01-01
  • 2010-11-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多