我想逐个字母连接2个不同的字符串。我怎样才能做到这一点?
例如:a = "hid", b = "jof"
串联字符串应为"hjiodf"
。
到目前为止,我已经做了很多尝试:
#include <stdio.h>
#include <conio.h>
void concatenate2(char p[], char q[]) {
int c = 0, d = 0;
//Iterating through both strings
while (p[c] != '\0' || q[d] != '\0' ) {
//Increment first string and assign the value
c++;
p[c] = q[d];
//Increment second string and assign the value
d++;
p[c] = q[d];
}
} //<<====== missing }
int main(void)
{
char w[100], a[100];
//input first string
printf("Input a string\n");
gets(w);
//input second string
printf("Input Second string\n");
gets(a);
//function call
concatenate2(w, a);
//print result
printf("String obtained on concatenation is \"%s\"\n", w);
getch();
return 0;
}
最佳答案
函数concatenate2
不能按编写的方式工作,因为它会在使用其字符之前覆盖目标缓冲区。
修改方式如下:
void concatenate2(char p[], const char q[]) {
int i, len = strlen(p);
p[len + len] = '\0';
for (i = len; i-- > 0;) {
p[i + i + 1] = q[i];
p[i + i] = p[i];
}
}
如果字符串的长度不同,则如何组合字符串的规范尚不清楚。
关于c - 如何将2个不同字符串中的字母逐个连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35678247/