用c语言编写程序编写一个函数char str_binchar str1 char str2 str1、str2是两个有序字符串其中字符按ASCII码从小到大排序将str2合并到字符串str1中要求合并后的字符串仍是有序的允许字符重复。在main函数中测试该函数:从键盘输入两个有序字符串然后调用该函数最后输出合并后的结果。
#include <stdio.h>
#include <string.h>
char* str_bin(char* str1, char* str2);
int main() {
char str1[100], str2[100];
printf("请输入第一个有序字符串:");
scanf("%s", str1);
printf("请输入第二个有序字符串:");
scanf("%s", str2);
char* result = str_bin(str1, str2);
printf("合并后的有序字符串为:%s", result);
return 0;
}
char* str_bin(char* str1, char* str2) {
int len1 = strlen(str1), len2 = strlen(str2);
char* new_str = (char*)malloc(sizeof(char) * (len1 + len2 + 1));
int i = 0, j = 0, k = 0;
while (i < len1 && j < len2) {
if (str1[i] <= str2[j]) {
new_str[k++] = str1[i++];
} else {
new_str[k++] = str2[j++];
}
}
while (i < len1) {
new_str[k++] = str1[i++];
}
while (j < len2) {
new_str[k++] = str2[j++];
}
new_str[k] = '\0';
return new_str;
}
``
原文地址: http://www.cveoy.top/t/topic/hoAA 著作权归作者所有。请勿转载和采集!