简体   繁体   English

使用C中的递归来反转字符数组

[英]Reverse a character array using recursion in C

Here's my code and I can't seem to figure out how to make the function with only the array as argument. 这是我的代码,我似乎无法弄清楚如何仅使用数组作为参数来构造函数。

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {

      char strArray[30] = "Print this string backward.";

      puts("");
      stringReverse(strArray);

      return(0);
}


void stringReverse(char strArray[])
{ 

    if(strArray != "\n") {
        stringReverse(&strArray)
        printf("%s", strArray)
    }
}

A few observations and criticisms: 一些观察和批评:

The math.h and stdlib.h header files are not needed for the posted code. 发布的代码不需要math.hstdlib.h头文件。 While char strArray[30] is large enough to hold the input string, it is better to use empty brackets in a string initializer unless you need a specific size that is larger than the initial string. 尽管char strArray[30]足够大,可以容纳输入字符串,但最好在字符串初始化程序中使用空括号,除非您需要的特定大小大于初始字符串。 This is less error-prone, and just easier, since there is no need to count characters, and no need to remember to include space for the null-terminator. 由于不需要对字符进行计数,也不需要记住要为空终止符包含空格,因此这种方法更不容易出错,也更容易实现。 You probably want to move the puts(""); 您可能想移动puts(""); to after the call to stringReverse() , since this function does not print a newline character. stringReverse()调用之后到,因为此函数不会打印换行符。 It usually seems better to use putchar('\\n'); 通常似乎最好使用putchar('\\n'); for something like this; 对于这样的事情; putchar() is designed to print only one character, and so is the right tool for the job. putchar()设计为仅打印一个字符,因此该作业也是正确的工具。

It seems that with the statement if (strArray != "\\n") {} the goal is to check if the first character is a newline, but there are a few problems with this. 似乎使用if (strArray != "\\n") {}语句的目的是检查第一个字符是否为换行符,但是这样做存在一些问题。 First, "\\n" is a string, not a character; 首先, "\\n"是字符串,而不是字符; next, strArray is a pointer to the first character of the array strArray[] , not the first character itself. 接下来, strArray是指向数组strArray[]的第一个字符的指针,而不是第一个字符本身。 There is no '\\n' character in the input string, so even if this condition were correctly written, it would always be true, and this code would enter an infinite recursion. 输入字符串中没有'\\n'字符,因此即使正确编写了此条件,它也将始终为true,并且此代码将输入无限递归。 Finally, the argument passed to stringReverse() is never changed, so there is no way for the recursion to end. 最后,传递给stringReverse()的参数永远不会改变,因此递归无法结束。 For recursion to succeed, a base case must be converged upon. 为了使递归成功,必须融合基本情况。

A solution is to compare the first character of the array with '\\0' . 一种解决方案是将数组的第一个字符与'\\0' If the first character is not the null-terminator, the stringReverse() function is called again, this time with the value strArray + 1 . 如果第一个字符不是null终止符,则再次调用stringReverse()函数,这次的值为strArray + 1 The program will continue recursively calling stringReverse() until an empty string is passed in, at which point the final call to stringReverse() returns to its caller (the previous call to stringReverse() ), where the last character of the string is printed, before returning to its caller,.... Each of the stringReverse() frames is returned to, in the reversed order in which they were called, and each of these frames prints a character of the string, until finally the first frame is reached, and the first character is printed, before returning to main() . 程序将继续递归调用stringReverse()直到传入空字符串为止,这时对stringReverse()的最终调用将返回到其调用方(对stringReverse()的上一次调用),在此打印字符串的最后一个字符在返回到其调用方之前,.....每个stringReverse()帧都以调用它们的相反顺序返回,并且这些帧中的每一个都打印字符串的字符,直到最后第一帧是到达并打印第一个字符,然后返回到main()

Note that in a function call, and in fact most expressions, arrays decay to pointers to their first elements. 请注意,在函数调用中,实际上在大多数表达式中,数组会衰减到指向其第一个元素的指针。 So, in stringReverse() strArray is a pointer to char that points to the first element of the array provided as an argument by the caller. 因此,在stringReverse() strArray是指向char的指针,该指针指向调用方作为参数提供的数组的第一个元素。 Also note that in a function declaration such as void stringReverse(char strArray[]) array types are adjusted to appropriate pointer types, so this declaration is equivalent to void stringReverse(char *strArray) . 还要注意,在诸如void stringReverse(char strArray[])类的函数声明中,数组类型已调整为适当的指针类型,因此此声明等效于void stringReverse(char *strArray)

#include <stdio.h>

void stringReverse(char strArray[]);

int main(void)
{
    char strArray[] = "Print this string backwards.";

    stringReverse(strArray);
    putchar('\n');

    return 0;
}

void stringReverse(char strArray[])
{
    if (*strArray != '\0') {
        stringReverse(strArray + 1);
        putchar(*strArray);
    }
}

Program output: 程序输出:

.sdrawkcab gnirts siht tnirP

First, you need to return an value. 首先,您需要返回一个值。

Then, what your algorithm should to do? 那么,您的算法应该怎么做? Run until the final of your string and then return variable by variable in reverse with just one parameter, well you just need pass this parameter shorter every loop. 运行到字符串的末尾,然后仅使用一个参数以逐个变量的方式返回变量,那么您只需要在每个循环中将此参数传递得更短即可。

Like this: 像这样:

#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"

void stringReverse(char strArray[], int i) {
    if (strArray[0] != NULL)
    if (strArray[0] != '\0') {
        int c = 0;
        char str[30];
        while (c < strlen(strArray)) {
            str[c] = strArray[2 + c -1];
            c++;
        }
        str[c] = '\0';
        stringReverse(str);
    }           
printf("%c", strArray[0]);
}

int main(int argc, char *argv[]) {
    char strArray[30] = "Print this string backward.";
   stringReverse(strArray, 0);
   printf("\n\n");
   system("Pause");
   return(0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM