- Home /
How to shuffle the charaters within words whilst not changing the position of all white spacing
Hi, I am currently experimenting with a word jumble/anagram game. currently, my code jumbles a word but will also shuffle the white spaces (which is what I do not what). Here is an example of what my code does and what I am trying to achieve:
A WORD: happy birthday // random word
JUMBLED VERSION(Using my current code): t dayhphbarpyi // jumbled word which loses spacing position
WHAT I AM TRYING TO ARCHIVE: tdayh phbarpyi // a jumbled word but correct spacing position remain*s*
Here is a snippet of my code which handles the shuffling:
void SetJumbledWord()
{
char[] myChar = currentEntry.word.ToCharArray(); // Convert string to char array
// Jumble char array
for (int i = myChar.Length - 1; i > 0; i--)
{
int rnd = Random.Range(0, i);
char temp = myChar[i];
myChar[i] = myChar[rnd];
myChar[rnd] = temp;
}
jumbledWord = new string(myChar); // Convert char array to string
jumbleWordText.text = jumbledWord; // Display jumbled word to screen
}
Answer by Dragate · Aug 19, 2019 at 06:09 PM
Just do a check for spacing before you do a swap.
for (int i = myChar.Length - 1; i > 0; i--){
int rnd = Random.Range(0, i);
char temp = myChar[i];
if(temp != ' ' && myChar[rnd] != ' '){
myChar[i] = myChar[rnd];
myChar[rnd] = temp;
}
}
Thanks for the feedback. Plugged your response into my code and looks like its producing the correct results. Will do some more testing just to be sure. Thank you for your help!
Your answer
![](https://koobas.hobune.stream/wayback/20220612210852im_/https://answers.unity.com/themes/thub/images/avi.jpg)