C 语言字符串合并:有序字符串合并函数实现
#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;
}
代码说明:
- 函数
str_bin: 该函数接收两个有序字符串str1和str2作为参数,返回一个新字符串,该字符串包含了str1和str2中的所有字符,并保持有序。 - 内存分配: 在函数内部,使用
malloc函数分配足够的空间来存储新的合并字符串。 - 合并逻辑: 使用三个指针
i、j和k分别遍历str1、str2和new_str。循环比较str1和str2中的字符,将较小的字符添加到new_str中,并移动相应指针。 - 处理剩余字符: 当一个字符串遍历完后,将另一个字符串的剩余字符添加到
new_str中。 - 添加结束符: 在
new_str的末尾添加字符串结束符\0。 - 返回新字符串: 函数返回新分配的字符串指针
new_str。
测试用例:
假设用户输入的两个有序字符串为:
str1 = 'abc'
str2 = 'def'
程序将输出:
合并后的有序字符串为:abcdef
注意:
在使用完 malloc 分配的内存后,需要使用 free 函数释放内存,避免内存泄漏。
free(result); // 释放内存
原文地址: https://www.cveoy.top/t/topic/oRp0 著作权归作者所有。请勿转载和采集!