我使用 fgets() 获取用户输入并将其存储到临时数组中。然后我将它连接到一个名为 userInput 的主数组,以便用户可以输入多行。

假设用户输入以下内容:

This is a sentence
This is a new line

我需要它按照输入的顺序打印每一行,但反转单词的顺序,如下所示:
sentence a is This
line new a is This

我有当前的方法,但我明白了:
line
new a is sentence
This a is This

下面是我用一个字符串调用 reversePrint() 来反转的代码:
void printToSpace(const char *str) {
  do {
    putc(*str, stdout);
  } while(*str++ != ' ');
}

void reversePrint(const char *str) {
  const char *p = strchr(str, ' ');
  if (p == NULL) {
    printf("%s", str);
  }
  else {
    reversePrint(p + 1);
    printToSpace(str);
  }
}

最佳答案

这是另一种方法:

#include <stdio.h>
#include <string.h>

void reversePrint(const char *str)
{
    if (str)
    {
        reversePrint(strtok (NULL, " \t\n\r"));
        printf("%s ", str);
    }
}

int main(void)
{
    char string[] = "This is a sentence";
    reversePrint(strtok(string, " \t\n\r"));
    return 0;
}

它看起来如此清晰和简单,我怀疑 strtok() 是否是为这样的需求而生的。

关于c - 以相反的顺序打印字符串中的单词 C,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35497332/

10-12 17:57