字符串中字词的反序 [英] Reverse order of words in string
问题描述
我正在准备一个入门级的面试。我试图扭转字符串中的单词的顺序,但我的输出是一堆垃圾,没有意义。我认为问题可能是因为我使用char *我的功能?反正我的代码
I am preparing for an entry-level job interview. I am trying to reverse the order of words in a string, but my output is a bunch of junk that makes no sense. I think the problem may be because I'm using "char*" for my functions? Anyways, heres my code
#include <iostream>
#include <string>
using namespace std;
char* reverse(char* str, int a, int b);
char* reversewords(char* str);
int main()
{
char str[] = "The interview is";
cout<<"Reverse is: "<<reversewords(str);
cin.ignore();
return 0;
}
char* reverse(char* str, int a, int b)
{
int length = a-b;
for (int i=a; i<b+1; i++)
{
char c =str[length-i-1];
str[length-i-1]=str[i];
str[i] = c;
}
return str;
}
char* reversewords(char* str)
{
int length = strlen(str);
int a=0;
int b=0;
while (b<length)
{
if (str[b]==' ' || b==length-1)
{
b=b-1;
reverse(str, a, b);
a=b+2;
b=a;
}
b++;
}
return str;
}
推荐答案
WeaselFox说不要重新发明轮子,尝试学习C ++ STL,从长远来看会更有帮助。
I would like to reiterate what WeaselFox said about not reinventing the wheel, try to learn the C++ STL, in the long run that will be a lot more helpful.
说到这里,让我建议一种方法以及。每当你遇到像字符串中的字符倒序或字符串中的字符颠倒的问题,采访者真的试图测试你的数据结构的知识,在这种情况下,特别是堆栈数据结构。
Having said that let me suggest an approach as well. Whenever you come across problems like reversing order of chars in a string OR reversing words in a string, interviewers are really trying to test your knowledge of data structures, and in this case, specifically the "stack" data structure.
考虑如果你解析一个字符串中的单词并将它们一次放入一个数组,会发生什么:
I AM A STRING - > {I AM,A,STRING}
Consider what happens if you parse words in a string and place them all into an array one at a time: "I AM A STRING" --> {"I", "AM", "A", "STRING"}
现在为堆叠做同样的事情:
Now do the same thing for a stack:
I AM A STRING - > {STRING,A,AM,I}
"I AM A STRING" --> {"STRING", "A", "AM", "I"}
有用吗?如果你自己比我提供源代码更好,原因是你的方法是不正确的,无论是否产生正确的答案。
Do you see why a stack would be useful ? It's better if you reason it out yourself than I provide source code, the reason being that your approach is incorrect regardless of whether or not it yields the correct answer.
我希望这有助于!
这篇关于字符串中字词的反序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!