Q: in a given string, swap the second word with the one before the last. if there are less than 4 words then just delete the second one
ex: "my name is laura fidarova" = "my laura is name fidarova"
i have the code, but my teacher said it's way too complicated. is there a way to write it without using <iterator>, <list> and <regex>?
#include <regex>
#include <iterator>
#include <iostream>
#include <string>
#include <list>
usingnamespace std;
int main()
{
string s = "My name is Laura Fidarova";
//string s = "My name is Laura";
//string s = "I am Laura";
// string s = "Laura Fidarova";
// string s = "Laura";
regex words_regex("[^\\s]+");
list<string> words;
for (sregex_iterator i = sregex_iterator(s.begin(), s.end(), words_regex); i != sregex_iterator(); ++i)
{
words.emplace_back(i->str());
}
auto words_begin = words.begin(), words_end = words.end();
if (words.size() < 4 && words.size() > 1)
{
words.erase(++words_begin);
}
elseif (words.size() > 3)
{
--words_end;
iter_swap(++words_begin, --words_end);
}
s.clear();
for (auto& word : words)
{
s += (word + " ");
}
cout << "Transformed text: " << s << endl;
read the words into a vector of string, letting cin split it on the whitespace for you.
swap the strings at the 2 locations with std:: swap.
write out the vector, injecting a space for each element.
you can do it character by character with no tools at all, if you must. Tools good. No tools bad. Regex too much sledgehammer for fly, though. Tool-less, creating a new string and jumping around in the original seem simple enough, just append the new characters to the new string in the right order.
#include <iostream>
#include <sstream>
#include<vector>
#include<string>
std::string get(std::string s )
{
std::istringstream sentence(s);
std::string v="",answer="";;
std::vector<std::string> vs;
int n;
while(sentence>>v)
{
n+=1;
vs.resize(n);
vs[n-1]=v+" ";
}
if (vs.size()<2) return"";
if (vs.size()<4) vs[1]="";
else
{swap (vs[1],vs[vs.size()-2]);}; //swap second with second last
for(n=0;n<vs.size();n++) answer=answer+vs[n];// build the answer
return answer;
}
int main()
{
std::string z=get("My name is Laura Fidarova");
std::cout<<z<<std::endl;
//end
std::cout <<"Press return to end . . ."<<std::endl;
std::cin.get();
}