Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Random-method causes "hidden dash"

Tags:

string

c#

random

I'm trying to generate a random string with 8 characters with the following method and it works perfectly, but It's 1 little problem.

When I'm printing the string to the screen and copying it from IE to Notepad, sometimes a dash (-) gets added in the middle of the string. What causes this and how can I fix it?

It doesn't happen alot, maybe 1/10 times , but still, it messes up the string.

    public string generateString()
    {
        int length = 8;
        string str = "";

        string chars = "abcdefghijkmnopqrstuvwxyzABCDEFGH­JKLMNOPQRSTUVWXYZ123456789";

        int charsCount = chars.Length;
        Random random = new Random();
        for (int i = 0; i < length; i++)
        {
            str += chars[random.Next(0, charsCount)];
        }

        return str;
    }
like image 328
user709712 Avatar asked Dec 10 '22 08:12

user709712


1 Answers

The code you've shown won't do add anything odd to the string. Perhaps it's the way you're copying and pasting which is causing a problem. If it's causing a problem occasionally, look at the HTML source (right-click, View Source) and see whether you can see the problem in there.

EDIT: As Henk has found out, your code apparently isn't all it seems. How did you end up with the strange character in your source code to start with?


Having said that, there are certainly things I would change about your code:

  • I'd make the name follow .NET naming conventions
  • I'd take the Random as a parameter, so you can call it multiple times in quick succession without generating the same string multiple times
  • I'd create a char array of the right length, populate it, and then create a new string from that instead of using string concatenation
  • I'd make the length of string to generate, and possibly even the character set parameters.

Just to give some idea of what it would look like - in this example I haven't turned the character set into a parameter, but I've extracted it from the method:

private const string ValidCharacters =
    "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";

public static string GenerateString(Random random, int length)
{
    // TODO: Argument validation
    char[] chars = new char[length];
    for (int i = 0; i < chars.Length; i++)
    {
        chars[i] = ValidCharacters[random.Next(ValidCharacters.Length)];
    }
    return new string(chars);
}
like image 135
Jon Skeet Avatar answered Dec 11 '22 23:12

Jon Skeet