c++ - 使用指针按单词反转字符串

标签 c++ pointers

我下面的程序反转了一个字符串,不是按字符而是按单词。

示例输入 你好梅洛 样本输出 Hello Mello Hello

我不知道我从哪里得到第一个 Hello。

#include "stdafx.h"
#include <iostream>

int main(int argc, char **argv)
{
  char input[255];
  char *head; // head of a word.
  char *tail; // tail of a word.

  printf("Enter a sentence: ");
  gets_s(input); // read a whole line.
  tail = input + strlen(input) - 1;

  while (tail >= input) 
    {
      if (*tail == 0 || *tail == ' ') 
        {
          tail--; // move to the tail of a word.
        }
      else 
        {
          tail[1] = 0;
          head = tail;
          while (head >= input) 
            {
              if (head == input || *(head - 1) == ' ') 
                {
                  printf("%s",input); // output a word.
                  printf(" ");

                  tail = head - 1; // seek the next word.
                  break;
                }
              head--; // move to the head of a word.
            }
        }
    }

  printf("\n\n");
  system("pause");
  return 0;
}

有人能帮忙吗?

最佳答案

我认为你的意思是 printf head,而不是输入。您是从字符串的开头打印,而不是从您刚找到的单词的开头打印。

printf("%s",head); // output a word.

关于c++ - 使用指针按单词反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27951839/

相关文章:

c++ - nuwen.net MinGW Distro 中没有 `fileno()` 功能?

c++ - stat(char[], stat) 当 string.c_str() = "c:/"时返回 -1

c++ - 在 std::for_each 中使用 std::bind

c - 指向函数的 Typedef 结构指针 (C)

c++ - 如何判断文本文件是否有Unicode BOM?

c++ - 保证内联静态 Meyers 单例的对象生命周期,并明确放置在一个部分中?

c - 在c中打印字符串指针

c - C 中的指针,异常行为

c - 使用 malloc 动态分配字符串

c++ - 双 * android ndk 崩溃