使用递归函数反转字符串 [英] Reverse a string using a recursive function
问题描述
我目前正在研究C和我不能让过去这个练习。我必须创建一个递归函数来扭转字符串1
到字符串2
。这里是我的code。我很乐意AP preciate你的帮助。
的#include<&stdio.h中GT;
#定义MAX 100void反转(字符S1 [],CHAR S2 [],INT N,诠释J);诠释的main()
{
字符字符串1 [MAX] =你怎么伴侣;
字符字符串2 [MAX] =;
INT N = 0;
INT I = 0;
INT J = 0; 对于(i = 0;字符串1 [I] ='\\ 0';!我++)
Ñ++;
反向(字符串1,字符串,N,J);
的printf(字符串正常的:\\ n%S \\ n字符串1);
的printf(字符串反向:\\ n%S \\ n,字符串2);
返回0;
}void反转(字符S1 [],CHAR S2 [],诠释N,诠释J)
{
如果(N 0)
{
S2 [J] = S1 [N];
扭转(S1,S2,正1,J + 1);
}
其他
S2 [J] ='\\ 0';
}
在倒车开始通过复制 N
的-th字符字符串1
数组字符串2
。在 N
-th性格恰好是空终止。它成为你新的字符串的第一个字符,因此字符串看上去是空的所有标准C例程,包括的printf
。
呼叫
反向(字符串1,字符串,N-1,J);
从主
应该解决这个问题。在逆转
应改变,如果(N大于0)的条件
到如果( ñ方式> = 0)
以及
I am currently studying C and I can't get past this exercise. I must create a recursive function to reverse string1
into string2
. Here is my code. I would gladly appreciate your help.
#include <stdio.h>
#define MAX 100
void reverse(char s1[],char s2[],int n,int j);
int main()
{
char string1[MAX]="How Are You Mate";
char string2[MAX]="";
int n=0;
int i=0;
int j=0;
for(i=0;string1[i]!='\0';i++)
n++;
reverse(string1,string2,n,j);
printf("String-a normal:\n%s\n",string1);
printf("String-a reverse:\n%s\n",string2);
return 0;
}
void reverse(char s1[],char s2[],int n,int j)
{
if(n>0)
{
s2[j]=s1[n];
reverse(s1,s2,n-1,j+1);
}
else
s2[j]='\0';
}
The reversing starts by copying the n
-th character of string1
array into string2
. The n
-th character happens to be the null terminator. It becomes the first character of your new string, so the string looks empty to all standard C routines, including printf
.
Calling
reverse(string1,string2,n-1,j);
from the main
should fix the problem. The condition in the reverse
should be changed from if(n>0)
to if(n>=0)
as well.
这篇关于使用递归函数反转字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!