swap two parts of a string

Nov 13, 2020 at 9:20pm
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 Nov 13, 2020 at 9:22pm
Nov 13, 2020 at 9:36pm
Find the space with string::find, then create the new string using string::substr.
Look up those methods.
Nov 14, 2020 at 11:35am
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 Nov 14, 2020 at 11:37am
Nov 14, 2020 at 11:51am
Just for the sheer fun of it, here's std::rotate.
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};
    test2+=' ';
    std::rotate(test2.begin(), test2.begin() + test2.find(' '), test2.end());

    std::cout << test2;
}

Nov 14, 2020 at 11:56am
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 Nov 14, 2020 at 11:56am
Nov 14, 2020 at 11:57am
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 Nov 14, 2020 at 12:00pm
Nov 14, 2020 at 2:55pm
Thank you all so much for helping me, really appreciate it :)
Topic archived. No new replies allowed.