Click here to Skip to main content
15,885,278 members
Articles / Multimedia / GDI

Sample Code to Scramble a Word using C# String object

Rate me:
Please Sign up or sign in to vote.
2.89/5 (6 votes)
19 Sep 2014CPOL 28.8K   4   6
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:

C#
 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:

C#
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).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
Tony is a seasoned .NET developer who recently switched his focus to Windows 8 and SEO. You may visit his technology websites: www.dotnetspider.com and www.techulator.com.

Comments and Discussions

 
GeneralThoughts Pin
PIEBALDconsult19-Sep-14 4:19
mvePIEBALDconsult19-Sep-14 4:19 
Make the Random a private static field.


Use a StringBuilder.


What you present will always return the last character last; "rand.Next(0, word.Length - 1)" should not have the "- 1" .

"A 32-bit signed integer greater than or equal to minValue and less than maxValue"
http://msdn.microsoft.com/en-us/library/2dx6wyd4(v=vs.110).aspx[^]


Substring and other string manipulation is not a good idea, especially in a loop. Remember that in .net, strings are immutable, so a statement like:
"word = word.Substring(0, next) + word.Substring(next + 1);"
involves instantiating a total of three new strings -- the first Substring, the second Substring, and the combined result. Two of them are immediately thrown away, the other will be thrown away on the next cycle.


Consider the following:

C#
private static System.Random rand = new System.Random();

public string ScrambleWord(string word)
{
    System.Text.StringBuilder result = new System.Text.StringBuilder ( word.Length ) ;

    System.Collections.Generic.List<char> chars = new System.Collections.Generic.List<char> ( word ) ;

    while ( chars.Count > 0 )
    {
        int next = rand.Next ( 0 , chars.Count ) ;
        result.Append ( chars [ next ] ) ;
        chars.RemoveAt ( next ) ;
    }

    return result.ToString() ;
}


This replaces the string manipulation with List manipulation, which ought to be more efficient.
GeneralMy vote of 1 Pin
Prerak Patel19-Sep-14 4:08
professionalPrerak Patel19-Sep-14 4:08 
GeneralRe: My vote of 1 Pin
Thanks787219-Sep-14 7:07
professionalThanks787219-Sep-14 7:07 
SuggestionLINQ does this in just one line Pin
Prerak Patel19-Sep-14 4:07
professionalPrerak Patel19-Sep-14 4:07 
QuestionHi Pin
alejandro29A19-Sep-14 3:30
alejandro29A19-Sep-14 3:30 
QuestionWhy not as an extension method ? Pin
Catalin Hatmanu19-Sep-14 3:15
Catalin Hatmanu19-Sep-14 3:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.