我正准备参加入门级面试。我试图扭转字符串中单词的顺序,但我的输出是一堆没有意义的垃圾。我认为问题可能是因为我正在使用“char *”作为我的功能?无论如何,继承我的代码
#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;
}
答案 0 :(得分:5)
我想重申WeaselFox所说的不重新发明轮子,尝试学习C ++ STL,从长远来看会更有帮助。
话虽如此,我也建议采用一种方法。每当遇到诸如在字符串中反转字符顺序或在字符串中反转单词等问题时,访调员就会尝试测试您对数据结构的了解,在这种情况下,特别是“堆栈”数据结构。
考虑如果解析字符串中的单词并将它们全部放入一个数组中,会发生什么: “我很棒” - &gt; {“我”,“AM”,“A”,“STRING”}
现在对堆栈做同样的事情:
“我是一个字符串” - &gt; {“STRING”,“A”,“AM”,“I”}
你知道为什么堆栈会有用吗?如果你自己推理出来比我提供源代码更好,原因是你的方法是不正确的,无论它是否产生正确的答案。
我希望这有帮助!
答案 1 :(得分:2)
如果您想要一个类似C的解决方案,如果您需要定义自己的char
函数来反转字符串之间的字符串,则只能使用指针和reverse
类型的临时变量来执行此操作。两个指针。下面的代码简单地反转它接收的整个字符串(它可以被修改为仅反转范围[iterA,iterB)中的字符串)并且反转每个单词中的字母是该字符串。例如,首先撤消hello world!
!dlrow olleh
会导致reverse_words
内的world! hello
更正为#include <cstring>
#include <cctype>
using std::isspace;
using std::strlen;
void reverse(char *start, char *end)
{
for (char c; --end - start > 0; ++start) {
c = *start;
*start = *end;
*end = c;
}
}
void reverse_words(char *s)
{
char *end = s + strlen(s);
char *delimp;
// Don't reverse any leading/trailing space (e.g. a newline).
while (isspace(*s))
++s;
while ((isspace(*end) || !*end) && end - s > 0)
--end;
// Reverse the remaining string.
reverse(s, ++end);
// Reverse each word.
while (end - s > 0) {
// Skip leading space characters.
while (isspace(*s))
++s;
// Find the next space character.
delimp = s;
while (!isspace(*delimp) && *delimp)
++delimp;
// Reverse the word.
reverse(s, delimp);
// Point to the next space character (or the end of the string).
s = delimp;
} //while(end - s > 0)
} //void reverse_words(...)
。
std::reverse
您可以用库中的reverse
替换上面定义的reverse_words
函数。尽管如此,我还是包含了一个实现。使用范围{{1}}的实现可能更有用,并且使用上述代码实现起来应该不难。它留给读者练习。
答案 2 :(得分:1)
让我推荐一种不同的方法。如果你使用char指针:
strtok
将字符串拆分为char*
s。如果您选择使用字符串和STL容器,请参阅此问题,以便将字符串拆分为标记,并将其重新组合得很好:
最好不要重新发明轮子。使用库函数,不要自己操纵字符。
答案 3 :(得分:1)
// Maybe just take the words out of the string and put them back in reverse
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main() {
string a("This is my string to try and reverse");
// Reverse word order
vector<string> words;
string::size_type pos = 1;
while(pos != string::npos) {
pos = a.find(" ");
if(pos != string::npos) {
words.push_back(string(a.begin(),a.begin()+pos));
a.erase(a.begin(),a.begin()+pos+1);
}
else {
words.push_back(string(a.begin(),a.end()));
a.erase(a.begin(),a.end());
}
}
reverse(words.begin(), words.end());
for(int i=0; i<words.size(); i++) a.append(words[i].append(" "));
cout << a << endl;
return 0;
}
答案 4 :(得分:0)
将int length = a-b;
更改为int length = b-a+1;
中的reverse()
。
此外,你需要循环到中间,否则它将被反转两次,给出原始输出。
for (int i=a; i<=a+(b-a)/2; i++)
{
char c =str[a+length-i-1];
str[a+length-i-1]=str[i];
str[i] = c;
}
答案 5 :(得分:0)
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
void split(string &str, vector<string> &v, char ch);
int main() {
string str;
std::getline(std::cin, str);
vector <string> stringVec;
split(str, stringVec, ' ');
vector <string>::reverse_iterator it;
for (auto it = stringVec.rbegin(); it != stringVec.rend();
++it)
{
cout << *it << " ";
}
return 0;
}
void split(string &str, vector<string> &v, char ch)
{
size_t pos = str.find(" ");
size_t initialpos = 0;
v.clear();
while (pos != string::npos)
{
v.push_back(str.substr(initialpos, pos - initialpos));
initialpos = pos + 1;
pos = str.find(ch,initialpos);
}
v.push_back(str.substr(initialpos, (std::min(pos, str.size()) -
initialpos + 1)));
}
答案 6 :(得分:-1)
为了让您了解如何使用RECURSION反转字符串,IN修改了下面给出的代码。学习并感受递归的力量。
#include <iostream>
#include <string>
using namespace std;
char * reverse_s(char *, char*, int,int);
int main()
{
char str[] = "The interview is";
char* rev_str = new char[strlen(str)];
cout<<"\n\nFinal Reverse of '" << str << "' is -->"<< reverse_s(str, rev_str, 0, strlen(str)) << endl;
cin.ignore();
delete rev_str;
return 0;
}
char* reverse_s(char* str, char* rev_str, int str_index, int rev_index ) {
if(strlen(str) == str_index )
return rev_str;
str_index += 1;
rev_index -=1;
rev_str = reverse_s(str, rev_str, str_index, rev_index);
cout << "\n Now the str value is " << str[str_index-1] << " -- Index " << str_index-1;
rev_str[rev_index] = str[str_index-1];
cout << "\nReversed Value: " << rev_str << endl;
return rev_str;
}
答案 7 :(得分:-1)
这是我的版本
#include <iostream>
#include <vector> // template for list
#include <algorithm> // copy algorithm or revers
#include <sstream> //sstringstream
#include <iterator>// iterator
#include <fstream>
using namespace std;
/* overloading ostream operator operator */
ostream &operator<<(ostream&out, const vector<string> a){
static int i = 1;
out << "Case #" << i++ << ": ";
for (vector<string> ::const_iterator v = a.begin(); v != a.end(); v++)
out << *v;
return out;
}
void showElemnts(vector<string> vec, int line){
cout << "Case #" << line << " " << vec; // overloading operator for output vector
}
vector<string> reversWord(string &s){
istringstream processWordByWord(s); // store string in processWordByWord and store in events
vector<string> events; // store events here
string input;
while (processWordByWord >> input){
events.push_back(input);
events.push_back(" ");
}
events.pop_back(); // delete space
reverse(events.begin(), events.end());
return events;
}
int main(){
vector<string> a;
string Line;
ifstream dataInput("B-small-practice.in", ios::in);
ofstream dataOut("out.out");
int number;
getline(dataInput, Line); // skip first line
getline(dataInput, Line); // skip first line
while (!dataInput.eof())
{
dataOut << reversWord(Line)<<endl;
getline(dataInput, Line);
}
dataInput.close();
dataOut.close();
return 0;
}