C++ 以相反的顺序打印输入字符串单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14109176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing input string words in reverse order
提问by user1940749
Using if
andwhile
/do
-while
, my job is to print following user's inputs (string value) in reverse order.
使用if
和while
/ do
- while
,我的工作是以相反的顺序打印以下用户的输入(字符串值)。
For example:
例如:
input string value : "You are American" output in reverse order : "American are You"
输入字符串值:“你是美国人”以相反的顺序输出:“美国人是你”
Is there any way to do this?
有没有办法做到这一点?
I have tried
我试过了
string a;
cout << "enter a string: ";
getline(cin, a);
a = string ( a.rbegin(), a.rend() );
cout << a << endl;
return 0;
...but this would reverse the order of the words andspelling while spelling is not what I'm going for.
...但这会颠倒单词和拼写的顺序,而拼写不是我想要的。
I also should be adding in if
and while
statements but do not have a clue how.
我也应该添加if
和while
声明,但不知道如何添加。
回答by Aravind
The algorithm is:
算法是:
- Reverse the whole string
- Reverse the individual words
- 反转整个字符串
- 反转单个单词
#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;
}
回答by Alex Reynolds
Here is a C-based approach that will compile with a C++ compiler, which uses the stack to minimize creation of char *
strings. With minimal work, this can be adapted to use C++ classes, as well as trivially replacing the various for
loops with a do-while
or while
block.
这是一种基于 C 的方法,它将使用 C++ 编译器进行编译,该编译器使用堆栈来最小化char *
字符串的创建。只需最少的工作,就可以适应使用 C++ 类,以及for
用do-while
orwhile
块简单地替换各种循环。
#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] = '$ g++ -Wall test.c -o test
$ ./test
foo bar baz
baz bar foo
';
}
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] = '#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
';
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] = '#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;
}
}
', rev(word_buffer), fprintf(stdout, "%s\n", word_buffer);
else if (line[line_idx] == ' ')
word_buffer[word_buffer_idx] = '#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;
}
', 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;
}
To compile with a C++ compiler, and then use:
要使用 C++ 编译器进行编译,然后使用:
#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;
}
回答by Enski Boski
This example unpacks the input string one word at a time, and builds an output string by concatenating in reverse order. `
此示例一次解压输入字符串一个单词,并通过以相反的顺序连接来构建输出字符串。`
#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;
}
`
`
回答by molbdnilo
This uses exactly one each of if
and while
.
它使用的每一个正好if
和while
。
回答by Hammam Orabi
This code here uses string libraries to detect the blanks in the input stream and rewrite the output sentence accordingly
这里的代码使用字符串库来检测输入流中的空格并相应地重写输出语句
The algorithm is 1. Get the input stream using getline function to capture the spacecs. Initialize pos1 to zero. 2. Look for the first space in the input stream 3. If no space is found, the input stream is the output 4. Else, get the position of the first blank after pos1, i.e. pos2. 5. Save the sub-string bewteen pos1 and pos2 at the beginning of the output sentence; newSentence. 6. Pos1 is now at the first char after the blank. 7. Repeat 4, 5 and 6 untill no spaces left. 8. Add the last sub-string to at the beginning of the newSentence. –
算法是 1. 使用 getline 函数获取输入流以捕获空格。将 pos1 初始化为零。2. 寻找输入流中的第一个空格 3. 如果没有找到空格,则输入流为输出 4. 否则,获取 pos1 后第一个空格的位置,即 pos2。5、保存输出语句开头的pos1和pos2之间的子串;新句。6. Pos1 现在位于空白之后的第一个字符处。7. 重复 4、5 和 6,直到没有空格为止。8. 将最后一个子字符串添加到 newSentence 的开头。——
##代码##回答by funseiki
You might try this solutionin getting a vector
of string
's using the ' ' (single space) character as a delimiter.
您可以尝试这种解决方案中得到一个vector
的string
“使用S'(单个空格)字符作为分隔符。
The next step would be to iterate over this vector backwards to generate the reverse string.
下一步是向后迭代这个向量以生成反向字符串。
Here's what it might look like (split
is the string splitting function from that post):
这是它可能的样子(split
是该帖子中的字符串拆分函数):
Edit 2: If you don't like vector
s for whatever reason, you can use arrays (note that pointers can act as arrays). This example allocates a fixed size array on the heap, you may want to change this to say, double the size when the current word amount has reached a certain value.
编辑 2:如果您vector
出于某种原因不喜欢s,则可以使用数组(请注意,指针可以充当数组)。这个例子在堆上分配了一个固定大小的数组,你可能想改变这个,当当前字数达到一定值时,将大小加倍。
Solution using an array
instead of a vector
:
使用 aarray
而不是 a 的解决方案vector
:
Edit: Added includes, main
function, while
loop format
编辑:添加了包含、main
函数、while
循环格式