c - 以相反的顺序打印字符串中的单词 C

标签 c user-input

我使用 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/

相关文章:

c - Mingw 使用 malloc 作为结构体

c - 所有涉及指针的值和地址之间有什么区别?

用于提示和返回输入的 shell 函数

java - 将用户输入从 editText 传递到 xml 中的 editText

javascript - 如何使用javascript程序设置输入值

c - O(n) 时间内的双维数组排序

c - 将 const 变量的地址分配给非 const 指针

我可以调用带有 int 参数的长参数的函数吗?

c - 如何在C上打开用户输入的文本文件

c - getchar/putchar、gets/puts 和 fgets/fputs(C 语言)之间有什么区别?