Sample code to scramble a Word using C# String object
Are you looking for sample C# code to scramble a word like a jumble word puzzles the kids you use? Here is some sample C# code to scramble the letters in a word.
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 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 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)
{
// Get a random number between 0 and the length of the word.
int next = rand.Next(0, word.Length - 1);
// Take the character from the random position and add to our char array.
chars[index] = word[next];
// Remove the character from the word.
word = word.Substring(0, next) + word.Substring(next + 1);
++index;
}
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.
does it work for visual studio 10