Ignoring Spaces?

Hi! I'm new to this site :D
I need help figuring out how I can manipulate certain strings. This program here is supposed to randomly scramble any word/sentence input. However, I notice that even the empty spaces get moved; is there any way to stop that from happening? I would want the empty spaces to stay in their input positions. Thank you!

#include <iostream>
#include <string.h>
#include <ctime>
#include <cstdlib>
#include <fstream>
#include <string>

using namespace std;

int main()
{
string sentence;
cout << "Enter a sentence: ";
getline(cin, sentence);
int x,y = 0;

srand(time(NULL));

for(int x = 0; y < sentence.length()-1; y++)

{
swap(sentence.at(rand()%sentence.length()),sentence.at(rand()%sentence.length()));
}


cout << sentence;

return EXIT_SUCCESS;
}
One way to do it is to check if either of the characters is a space before swapping them and only swap if neither is a space. Another possibility is to store the locations of the spaces, remove them, scramble the string, then re-insert them. You could also break the sentence up into words and scramble the words individually.
I'm sorry I'm kind of new to this but how would I go about doing this? Does it involve == ' ' or something like this?
You must use two chars to compare them with ' '.
before
swap(sentence.at(rand()%sentence.length()),sentence.at(rand()%sentence.length()));
you must have a if like:
1
2
3
4
if (randomLetter1 != ' ' && randomLetter2 != ' ')
{
       //the swap code
}
The <algorithm> in the standard library has a function random_shuffle. Its reference documentation on this site shows an equivalent implementation, which differs from yours slightly.

The essential thing for ignoring the spaces is that rand()%sentence.length() is a number. Store it in a named variable. Then check, whether character in the string at that position can be swapped. If yes, then swap.
Topic archived. No new replies allowed.