节目输出将是这样的:
string1 : stack
string2 : overflow
changed string is : sotvaecrkf
* string1的每个第N个字符由string2的第N个字符连接
但是每次运行时我的DevC ++都会崩溃并向string1和string2提供输入
C代码:
#include<stdio.h>
#include<string.h>
void zips();
void main(){
zips();
}
void zips(){
printf("enter string1:");
char s1[120],s2[120],s[120],y,z;
scanf("\n%s",s1);
printf("\nenter string2:");
scanf("\n%s",s2);
int leng,increasedlength,i;
int leng1=strlen(s1),leng2=strlen(s2);
if(leng1==leng2){
leng=leng1;
}
else if(leng1<leng2){
increasedlength=leng2-leng1;
leng=leng2-increasedlength;
}
else{
increasedlength=leng1-leng2;
leng=leng1-increasedlength;
}
for(i=0;i<=leng;i++){
y=s1[i];
printf("%s",y);
z=s2[i];
printf("%s",z);
strcat(y,z);
}
}
答案 0 :(得分:2)
也许是这样的。请注意,无法在简单的char
类型上进行字符串连接。
#include <stdio.h>
#include <string.h>
int main (void) {
char s1[] = "stack"; // skipped the string inputs
char s2[] = "overflow";
char str[120];
size_t i; // var type returned by `strlen`
size_t index = 0;
size_t leng1 = strlen(s1);
size_t leng2 = strlen(s2);
size_t leng = leng1 <= leng2 ? leng1 : leng2; // ternary operation to get min length
if(leng == 0 || leng * 3 > sizeof str)
return 1; // will not fit output string
for(i = 0; i < leng; i++) { // note `<=` changed to `<`
str[index++] = s1[i]; // buiuld the output string
str[index++] = s2[i];
str[index++] = ' '; // pad string
}
str[index - 1] = '\0'; // terminate string
printf("%s\n", str);
return 0;
}
节目输出:
so tv ae cr kf