Q: " given a string. obtain another one by swapping the parts of the first one after the first entry of space"
so i guess it's like this:
input: basketball is a popular sport;
ootput: is a popular sport basketball;
how do i do that?
thanks in advance!)
Last edited on
Find the space with string::find, then create the new string using string::substr.
Look up those methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <string>
#include <iostream>
int main()
{
const std::string test {"basketball is a popular sport"};
std::string test1 {test};
const auto sp {test.find(' ')};
if (sp != std::string::npos)
test1.append(" ").append(test, 0, sp).erase(0, sp + 1);
std::cout << test << '\n';
std::cout << test1 << '\n';
}
|
basketball is a popular sport
is a popular sport basketball
|
Last edited on
Nice. Close - but has a leading space.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <string>
#include <iostream>
#include <algorithm>
int main()
{
const std::string test {"basketball is a popular sport"};
auto test2 {test + ' '};
std::rotate(test2.begin(), test2.begin() + test2.find(' ') + 1, test2.end());
std::cout << test2;
}
|
Last edited on
The instruction does say swap the parts AFTER the first space, which suggests that the first space shouldn't be going anywhere...
although the instruction also says nothing about adding a space on the end so that the last two words don't jam together.
To be honest, the instruction makes no sense whatsoever. This appears to also be a valid answer:
"basketball popular is sport a"
All the parts after the first space have been swapped :/
Last edited on
Thank you all so much for helping me, really appreciate it :)