gpt4 book ai didi

c - 在C中将两个字符串合并在一起,关闭字符

转载 作者:太空狗 更新时间:2023-10-29 15:55:12 27 4
gpt4 key购买 nike

我试图在 C 中合并两个可变长度的字符串。结果应该是 str1 的第一个字符,然后是 str2 的第一个字符,然后是 str1 的第二个字符,str2 的第二个字符,等等。当它到达一个字符串的末尾时它应该附加其他字符串的其余部分。

例如:

str1 = "abcdefg";
str2 = "1234";

outputString = "a1b2c3d4efg";

我是 C 的新手,我的第一个想法是将两个字符串都转换为数组,然后尝试遍历数组,但我认为可能有更简单的方法。示例代码将不胜感激。

更新:我试图实现下面的答案。我的函数如下所示。

void strMerge(const char *s1, const char *s2, char *output, unsigned int ccDest)
{
printf("string1 is %s\n", s1);
printf("string2 is %s\n", s2);

while (*s1 != '\0' && *s2 != '\0')
{
*output++ = *s1++;
*output++ = *s2++;
}
while (*s1 != '\0')
*output++ = *s1++;
while (*s2 != '\0')
*output++ = *s2++;
*output = '\0';

printf("merged string is %s\n", *output);
}

但是我在编译的时候得到一个警告:

$ gcc -g -std=c99 strmerge.c -o strmerge
strmerge2.c: In function ‘strMerge’:
strmerge2.c:41:5: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat]

当我运行它时它不起作用:

./strmerge abcdefg 12314135
string1 is abcdefg
string2 is 12314135
merged string is (null)

为什么它认为参数 2 是一个 int,我如何将它修复为一个 char?如果我删除 printf 中的“*”关闭输出,它不会给出编译错误,但该函数仍然不起作用。

最佳答案

下面的代码通过使输出字符串与两个输入字符串一样长来确保字符串不会溢出,并使用 fgets() 来确保输入字符串不会溢出.一种替代设计是进行动态内存分配(malloc() 等),代价是调用代码必须 free() 分配的空间。另一种设计是将输出缓冲区的长度传递给函数,以确保不会发生溢出。

测试程序不发出提示:添加一个函数来这样做并不难。

代码

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

void interleave_strings(const char *s1, const char *s2, char *output)
{
while (*s1 != '\0' && *s2 != '\0')
{
*output++ = *s1++;
*output++ = *s2++;
}
while (*s1 != '\0')
*output++ = *s1++;
while (*s2 != '\0')
*output++ = *s2++;
*output = '\0';
}

int main(void)
{
char line1[100];
char line2[100];
char output[200];
if (fgets(line1, sizeof(line1), stdin) != 0 &&
fgets(line2, sizeof(line2), stdin) != 0)
{
char *end1 = line1 + strlen(line1) - 1;
char *end2 = line2 + strlen(line2) - 1;
if (*end1 == '\n')
*end1 = '\0';
if (*end2 == '\n')
*end2 = '\0';
interleave_strings(line1, line2, output);
printf("In1: <<%s>>\n", line1);
printf("In2: <<%s>>\n", line2);
printf("Out: <<%s>>\n", output);
}
}

示例输出

$ ./interleave
abcdefgh
1234
In1: <<abcdefgh>>
In2: <<1234>>
Out: <<a1b2c3d4efgh>>
$

关于c - 在C中将两个字符串合并在一起,关闭字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18950495/

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