65.9K
CodeProject is changing. Read more.
Home

Sample Code to Scramble a Word using C# String object

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.89/5 (6 votes)

Sep 19, 2014

CPOL
viewsIcon

30028

This post shows sample code to scramble a word using C# string object

Introduction

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) 
    { // 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.

(This article was originally published here).