我想编写一个递归函数,它将2个字符串组合成一个按字母顺序排列的字符串,2个字符串只是小写字母,按升序字母顺序排列。示例: s1:“aegiz”s2:“abhxy”s3:“aabeghixyz”
我仍然是递归函数和C的新手,我认为这可以用比我更好的方式解决...
到目前为止我的代码:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define N 50
char *combinealph(char *str1, char *str2, char *str3);
void main()
{
char *str1[N], *str2[N],*str3;
int length;
printf("Enter first string:\n");
gets(str1);
printf("Enter second string:\n");
flushall(1);
gets(str2);
length = strlen(str1) + strlen(str2);
str3 = (char*)malloc((length+1)*sizeof(char));
printf("The combined string :\n");
puts(combinealph(str1, str2, str3));
getch();
}
char *combinealph(char *str1, char *str2, char *str3)
{
if (*str1 == '\0' && *str2 != '\0')
strcpy(str3, str2);
return str3;
if (*str1 != '\0' && *str2 == '\0')
strcpy(str3, str1);
return str3;
if (*str1 == '\0' && *str2 == '\0')
return '\0';
if (*str1 >= *str2)
{
strcpy(str3, str1);
return strcat(*str3, combinealph(str1 + 1, str2, str3+1));
}
if (*str1 < *str2)
{
*str3 = *str2;
return strcat(*str3, combinealph(str1, str2 + 1, str3+1));
}
}
答案 0 :(得分:2)
看来你的意思是以下
#include <stdio.h>
#include <string.h>
char * combine_strings( char *result, const char *s1, const char *s2 )
{
if ( *s1 == '\0' && *s2 == '\0' )
{
*result = '\0';
return result;
}
else if ( *s1 == '\0' )
{
*result++ = *s2++;
return combine_strings( result, s1, s2 ) - 1;
}
else if ( *s2 == '\0' )
{
*result++ = *s1++;
return combine_strings( result, s1, s2 ) - 1;
}
else
{
*result++ = *s2 < *s1 ? *s2++ : *s1++;
return combine_strings( result, s1, s2 ) - 1;
}
}
int main(void)
{
const char *s1 = "aegiz";
const char *s2 = "abhxy";
char result[ strlen( s1 ) + strlen( s2 ) + 1];
printf( "%s\n", combine_strings( result, s1, s2 ) );
return 0;
}
程序输出
aabeghixyz
您可以缩短功能。例如
char * combine_strings( char *result, const char *s1, const char *s2 )
{
if ( *s1 == '\0' && *s2 == '\0' )
{
*result = '\0';
return result;
}
else
{
*result++ = ( *s2 && *s2 < *s1 ) || !*s1 ? *s2++ : *s1++;
return combine_strings( result, s1, s2 ) - 1;
}
}