结合2串在另一个字符串按字母顺序
问题描述:
我想写结合2串入一个字符串,它是按字母顺序排列的2串都只是小字母和字母升序递归函数。例如: s1:“aegiz”s2:“abhxy”s3:“aabeghixyz”结合2串在另一个字符串按字母顺序
我对递归函数和C一般还不熟悉,我认为这可以比我做的更好地解决...
到目前为止我的代码:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define N 50
char *combinealph(char *str1, char *str2, char *str3);
void main()
{
\t char *str1[N], *str2[N],*str3;
\t int length;
\t printf("Enter first string:\n");
\t gets(str1);
\t printf("Enter second string:\n");
\t flushall(1);
\t gets(str2);
\t length = strlen(str1) + strlen(str2);
\t str3 = (char*)malloc((length+1)*sizeof(char));
\t printf("The combined string :\n");
\t puts(combinealph(str1, str2, str3));
\t getch();
}
char *combinealph(char *str1, char *str2, char *str3)
{
\t if (*str1 == '\0' && *str2 != '\0')
\t \t strcpy(str3, str2);
\t \t return str3;
\t if (*str1 != '\0' && *str2 == '\0')
\t \t strcpy(str3, str1);
\t \t return str3;
\t if (*str1 == '\0' && *str2 == '\0')
\t \t \t return '\0';
\t if (*str1 >= *str2)
\t {
\t \t strcpy(str3, str1);
\t \t return strcat(*str3, combinealph(str1 + 1, str2, str3+1));
\t }
\t if (*str1 < *str2)
\t {
\t \t *str3 = *str2; \t
\t \t return strcat(*str3, combinealph(str1, str2 + 1, str3+1));
\t }
}
答
看来,你指的是以下
#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;
}
}
什么是你的问题?关于提高代码的问题属于在代码审查http://codereview.stackexchange.com/ –
以及我的代码不能正常工作,所以我想我怎样才能使其正常工作是个问题? – n4tri0s
使函数成为'void'并去掉所有的'return's。摆脱'strcat's,也是。而你有'的strcpy(STR3,STR1);',你的意思是'* STR3 = * STR1;'(从底部5日线)..顺便说一句,你在执行操作称为 “合并”。 – ooga