【问题标题】:Concatenating strings in C在 C 中连接字符串
【发布时间】:2009-06-09 05:35:51
【问题描述】:

如何在 C 中连接字符串,不像 1 + 1 = 2 而是像 1 + 1 = 11

【问题讨论】:

  • 恐怕你的问题目前没有多大意义。能具体一点吗?
  • 感谢您编辑 Vinko,我想我会因为我的问题而被激怒,但实际上我得到了我想要的。感谢 stackoverflow.com
  • austin,您介意标记您接受的对您最有帮助的答案吗?
  • 当然,抱歉。这是我第一次使用 stackoverflow。

标签: c string concatenation


【解决方案1】:

我认为你需要字符串连接:

#include <stdio.h>
#include <string.h>

int main() {
  char str1[50] = "Hello ";
  char str2[] = "World";

  strcat(str1, str2);

  printf("str1: %s\n", str1);

  return 0;
}

来自:http://irc.essex.ac.uk/www.iota-six.co.uk/c/g6_strcat_strncat.asp

【讨论】:

  • 请注意,strncat()(带有'n')很难正确使用——所以不要使用它。
  • 为什么比在 strcat 中计算缓冲区更难?
  • @Jonathan:不知道“非常难”,但它更安全。
  • 没有很多更安全。 strlcat() 存在是有原因的。虽然这也不是一个完整的修复。这只是一个简单的改进。我会使用 snprintf()。它具有最佳行为。
  • strncat() 不保证结果为 nul 终止。 strlcat() 可以,但可能不会广泛使用。 strcat() 幸福地不知道目标缓冲区的大小。简而言之,C 标准库承载着大量阻碍防止缓冲区溢出的历史记录。
【解决方案2】:

要连接两个以上的字符串,可以使用 sprintf,例如

char buffer[101];
sprintf(buffer, "%s%s%s%s", "this", " is", " my", " story");

【讨论】:

  • 同理:snprintf 并非随处可用
  • 很多人只能依赖c89。甜蜜的 snprintf 对他们不可用 :(
【解决方案3】:

尝试查看 strcat API。如果有足够的缓冲区空间,您可以将一个字符串添加到另一个字符串的末尾。

char[50] buffer;
strcpy(buffer, "1");
printf("%s\n", buffer); // prints 1
strcat(buffer, "1");
printf("%s\n", buffer); // prints 11

strcat 的参考页面

【讨论】:

    【解决方案4】:

    'strcat' 是答案,但认为应该有一个明确涉及缓冲区大小问题的示例。

    #include <string.h>
    #include <stdlib.h>
    
    /* str1 and str2 are the strings that you want to concatenate... */
    
    /* result buffer needs to be one larger than the combined length */
    /* of the two strings */
    char *result = malloc((strlen(str1) + strlen(str2) + 1));
    strcpy(result, str1);
    strcat(result, str2);
    

    【讨论】:

    • 这会通过覆盖指针result 来泄漏内存,并且至少还需要一个strcpy()。此外,它扩展了 str1,但这意味着您希望 str1 和 str2 都是只读的。
    • malloc() 可能返回 NULL,导致 UB。
    【解决方案5】:

    strcat(s1, s2)。注意缓冲区大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-16
      • 2012-01-04
      • 1970-01-01
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多