shuffle a string in csharp

To shuffle a string in C#, we can convert the string into a char array, shuffle the array using a random number generator, and then convert the shuffled array back to a string.

Here's a code example:

main.cs
public static string ShuffleString(string str)
{
    // Convert string to char array
    char[] charArray = str.ToCharArray();
    
    // Shuffle the array
    Random rand = new Random();
    for (int i = 0; i < charArray.Length; i++)
    {
        int j = rand.Next(i, charArray.Length);
        char temp = charArray[i];
        charArray[i] = charArray[j];
        charArray[j] = temp;
    }
    
    // Convert char array back to string
    string shuffledStr = new string(charArray);
    return shuffledStr;
}
516 chars
20 lines

We first convert the input string into a char array using the ToCharArray method. We then use a Random object to generate random indexes and swap the characters at those indexes in the char array to shuffle it. Finally, we convert the shuffled char array back to a string using the new string(char[]) constructor and return the result.

gistlibby LogSnag