I was developing a small C# program to generate and print scrambled words puzzle for kids, which are generally called 'Jumbled Words' by many children. I was looking for some C# or VB.NET sample code to scramble the letters in the given word. For example, if the given word is "
POLICE", I should be able to randomly scramble the letters in the word and generate a new word something like this: "
COLPIE" or "
ICELPO". I found a couple of examples in various sites, but I wasn't convinved with most of them. So I decided to write a sample myself. Here is the code I came up with to scramble the given word to develop my Jumbled Words puzzle:
public string ScrambleWord(string word)
char chars = new char[word.Length];
Random rand = new Random(10000);
int index = 0;
while (word.Length > 0)
int next = rand.Next(0, word.Length - 1);
chars[index] = word[next];
word = word.Substring(0, next) + word.Substring(next + 1);
return new String(chars);
How to Call the string Scramble Method?
It is very easy to use the above method to scramble the words. See an example below:
string word = "POLICE"; string scrambled_Word = ScrambleWord(word);
This C# sample is short and efficient, compared to some other pretty big programs I could find on the web to scramble
strings. There is nothing specific to C# here, so you can easily change the syntax a bit to make your own VB.NET word scramble program.
(This article was originally published here).