This was part of a code challenge. I use them to help me learn c++/c# along with tutorials and guides. Basically I was taking a string...
The quick brown fox jumps over the lazy dog.
...and reversing the words in the string like this.
ehT kciuq nworb xof spmuj revo eht yzal .god
The following code works and compiles. However, I feel like this was a verbose way to achieve the objective.
split
This function was a copy paste from another Stack Overflow page. I'm not sure if this is idiomatic in c++, but it feels like an overkill. I just used it because it worked when I tested it on single word strings.
vector_to_string
I came up with this function because I had forgotten how to do this in c++. I recall a built in function somewhere in its library.
reverse_words
This was the provided function for the challenge. Everything inside of the {} is what I came up with.
Everything in the int main() I came up as well for testing. Test are provided, but I haven't quite learned how to implement this offline yet. Following is my code, with the test after that.
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<string> split(string s, string delimiter)
{
size_t pos_start = 0, pos_end, delim_len = delimiter.length();
string token;
vector<string> res;
while ((pos_end = s.find(delimiter, pos_start)) != string::npos)
{
token = s.substr(pos_start, pos_end - pos_start);
pos_start = pos_end + delim_len;
res.push_back(token);
}
res.push_back(s.substr(pos_start));
return res;
}
string vector_to_string(vector<string> v)
{
string s;
for (auto &e : v)
{
reverse(e.begin(), e.end());
s += e + " ";
}
return s;
}
string reverse_words(string str)
{
vector<string> v = split(str, " ");
string s = vector_to_string(v);
return s.substr(0, s.length() - 1);
}
int main()
{
cout << reverse_words("The quick brown fox jumps over the lazy dog.") << endl;
cout << reverse_words("apple") << endl;
cout << reverse_words("a b c d") << endl;
cout << reverse_words("") << endl;
cout << reverse_words("ab ba cd") << endl;
}
I was provided with these tests:
Describe(Tests) { It(Sample_Test_Cases) { Assert::That(reverse_words("The quick brown fox jumps over the lazy dog."), Equals("ehT kciuq nworb xof spmuj revo eht yzal .god")); Assert::That(reverse_words("apple"), Equals("elppa")); Assert::That(reverse_words("a b c d"), Equals("a b c d")); Assert::That(reverse_words("double spaced words"), Equals("elbuod decaps sdrow")); Assert::That(reverse_words(""), Equals("")); Assert::That(reverse_words("ab ba cd"), Equals("ba ab dc")); } };
Anyhow, any advice on this is much appreciated and thank you for your help. Again, I feel like this is a verbose way to solve this problem and I suspect it can be greatly optimized as well.