我正在尝试在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)
为什么它认为第二个参数是int,而我如何将其修复为char类型?如果我在printf中删除output前面的“*”,它就不会报编译错误,但该函数仍然无法正常工作。
output
而不是*output
(后者是字符串的第一个字符而不是整个字符串本身)。此外,output
指向字符串末尾的空字节。如果你想打印整个字符串,你必须在进入函数时保留output
的原始值。 - Jonathan Leffler