0

使用if and while / do- while,我的工作是以相反的顺序打印用户的输入(字符串值)。

例如:

输入字符串值:“你是美国人”以相反的顺序输出:“美国人是你”

有没有办法做到这一点?

我努力了

string a;
cout << "enter a string: ";
getline(cin, a);
a = string ( a.rbegin(), a.rend() );
cout << a << endl;
return 0;

...但这会颠倒单词拼写的顺序,而拼写不是我想要的。

我也应该添加ifwhile声明,但不知道如何。

4

6 回答 6

5

算法是:

  1. 反转整个字符串
  2. 反转单个单词
#include<iostream>
#include<algorithm>
using namespace std;

string reverseWords(string a)
{ 
    reverse(a.begin(), a.end());
    int s = 0;
    int i = 0;
    while(i < a.length())
    {
        if(a[i] == ' ')
        {
             reverse(a.begin() + s, a.begin() + i);
             s = i + 1;
        }
        i++;
    }
    if(a[a.length() - 1] != ' ')  
    {
        reverse(a.begin() + s, a.end());           
    }
    return a; 
}
于 2013-01-01T09:27:17.713 回答
1

这是一种基于 C 的方法,它将使用 C++ 编译器进行编译,该编译器使用堆栈来最小化char *字符串的创建。通过最少的工作,这可以适应使用 C++ 类,以及用 a或块轻松替换各种for循环。do-whilewhile

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

#define MAX_LINE_LENGTH 1000
#define MAX_WORD_LENGTH 80

void rev(char *str) 
{
    size_t str_length = strlen(str);
    int str_idx;
    char word_buffer[MAX_WORD_LENGTH] = {0};
    int word_buffer_idx = 0;

    for (str_idx = str_length - 1; str_idx >= 0; str_idx--)
        word_buffer[word_buffer_idx++] = str[str_idx];

    memcpy(str, word_buffer, word_buffer_idx);
    str[word_buffer_idx] = '\0';
}

int main(int argc, char **argv) 
{
    char *line = NULL;
    size_t line_length;
    int line_idx;
    char word_buffer[MAX_WORD_LENGTH] = {0};
    int word_buffer_idx;

    /* set up line buffer - we cast the result of malloc() because we're using C++ */

    line = (char *) malloc (MAX_LINE_LENGTH + 1);
    if (!line) {
        fprintf(stderr, "ERROR: Could not allocate space for line buffer!\n");
        return EXIT_FAILURE;
    }

    /* read in a line of characters from standard input */

    getline(&line, &line_length, stdin);

    /* replace newline with NUL character to correctly terminate 'line' */

    for (line_idx = 0; line_idx < (int) line_length; line_idx++) {
        if (line[line_idx] == '\n') {
            line[line_idx] = '\0';
            line_length = line_idx; 
            break;
        }
    }

    /* put the reverse of a word into a buffer, else print the reverse of the word buffer if we encounter a space */

    for (line_idx = line_length - 1, word_buffer_idx = 0; line_idx >= -1; line_idx--) {
        if (line_idx == -1) 
            word_buffer[word_buffer_idx] = '\0', rev(word_buffer), fprintf(stdout, "%s\n", word_buffer);
        else if (line[line_idx] == ' ')
            word_buffer[word_buffer_idx] = '\0', rev(word_buffer), fprintf(stdout, "%s ", word_buffer), word_buffer_idx = 0;
        else
            word_buffer[word_buffer_idx++] = line[line_idx];
    }

    /* cleanup memory, to avoid leaks */

    free(line);

    return EXIT_SUCCESS;
}

要使用 C++ 编译器进行编译,然后使用:

$ g++ -Wall test.c -o test
$ ./test
foo bar baz
baz bar foo
于 2013-01-01T09:50:07.977 回答
1

此示例一次将输入字符串解包一个单词,并通过以相反的顺序连接来构建输出字符串。`

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
  string inp_str("I am British");
  string out_str("");
  string word_str;
  istringstream iss( inp_str );


  while (iss >> word_str) {
    out_str = word_str + " " + out_str;
  } // while (my_iss >> my_word) 

  cout << out_str << endl;

  return 0;
} // main

`

于 2015-10-21T06:04:27.233 回答
0

您可以尝试使用此解决方案来获取vector使用string' '(单个空格)字符作为分隔符的 '。

下一步将是向后迭代该向量以生成反向字符串。

下面是它的样子(split是该帖子中的字符串拆分函数):

编辑 2:如果您出于某种原因不喜欢vectors,则可以使用数组(请注意,指针可以充当数组)。这个例子在堆上分配了一个固定大小的数组,你可能想把它改成当当前字数达到某个值时,大小加倍。

使用 aarray而不是 a 的解决方案vector

#include <iostream>
#include <string>
using namespace std;

int getWords(string input, string ** output)
{
    *output = new string[256];  // Assumes there will be a max of 256 words (can make this more dynamic if you want)
    string currentWord;
    int currentWordIndex = 0;
    for(int i = 0; i <= input.length(); i++)
    {
        if(i == input.length() || input[i] == ' ')  // We've found a space, so we've reached a new word
        {
            if(currentWord.length() > 0)
            {
                (*output)[currentWordIndex] = currentWord;
                currentWordIndex++;
            }
            currentWord.clear();
        }
        else
        {
            currentWord.push_back(input[i]);    // Add this character to the current word
        }
    }
    return currentWordIndex;    // returns the number of words
}

int main ()
{
    std::string original, reverse;
    std::getline(std::cin, original);  // Get the input string
    string * arrWords;
    int size = getWords(original, &arrWords);  // pass in the address of the arrWords array
    int index = size - 1;
    while(index >= 0)
    {
       reverse.append(arrWords[index]);
       reverse.append(" ");
       index--;
    }
    std::cout << reverse << std::endl;
    return 0;
}

编辑:添加包含、main功能、while循环格式

#include <vector>
#include <string>
#include <iostream>
#include <sstream>


// From the post
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems)
{
   std::stringstream ss(s);
   std::string item;
   while(std::getline(ss, item, delim)) {
       elems.push_back(item);
   }
   return elems;
}


std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    return split(s, delim, elems);
}

int main ()
{
    std::string original, reverse;
    std::cout << "Input a string: " << std::endl;
    std::getline(std::cin, original);  // Get the input string

    std::vector<std::string> words = split(original, ' ');

    std::vector<std::string>::reverse_iterator rit = words.rbegin();

    while(rit != words.rend())
    {
       reverse.append(*rit);
       reverse.append(" "); // add a space
       rit++;
    }
    std::cout << reverse << std::endl;
    return 0;
}
于 2013-01-01T09:30:40.453 回答
0

这仅使用 和 中的if一个while

#include <string>
#include <iostream>
#include <sstream>


void backwards(std::istream& in, std::ostream& out)
{
   std::string word;
   if (in >> word)   // Read the frontmost word
   {
      backwards(in, out);  // Output the rest of the input backwards...
      out << word << " ";  // ... and output the frontmost word at the back
   }
}

int main()
{
   std::string line;
   while (getline(std::cin, line))
   {
      std::istringstream input(line);
      backwards(input, std::cout);
      std::cout << std::endl;
   }
}
于 2013-01-01T15:41:24.570 回答
0

这里的代码使用字符串库来检测输入流中的空白并相应地重写输出语句

算法是 1. 使用 getline 函数获取输入流以捕获 spacecs。将 pos1 初始化为零。2.在输入流中查找第一个空格 3.如果没有找到空格,则输入流是输出 4.否则,获取pos1之后第一个空格的位置,即pos2。5. 保存输出句首pos1和pos2之间的子串;新句。6. Pos1 现在位于空白后的第一个字符处。7. 重复 4、5 和 6,直到没有空格。8. 将最后一个子字符串添加到 newSentence 的开头。–

#include <iostream> 
#include <string> 

  using namespace std; 

int main ()
{ 
    string sentence; 
    string newSentence;
    string::size_type pos1; 
    string::size_type pos2; 

    string::size_type len; 

    cout << "This sentence rewrites a sentence backward word by word\n"
            "Hello world => world Hello"<<endl;

    getline(cin, sentence); 
    pos1 = 0; 
    len = sentence.length();
    pos2 = sentence.find(' ',pos1); 
    while (pos2 != string::npos)
        {
            newSentence = sentence.substr(pos1, pos2-pos1+1) + newSentence; 
            pos1 = pos2 + 1;
            pos2 = sentence.find(' ',pos1);       
        }
    newSentence = sentence.substr(pos1, len-pos1+1) + " "  + newSentence;
    cout << endl << newSentence  <<endl; 

    return 0;

}
于 2015-06-08T09:02:13.157 回答