user709712
user709712

Reputation: 253

C# Random-method causes "hidden dash"

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;
    }

Upvotes: 4

Views: 543

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273571

After a little poking around, the following line is not what it seems. Between the letters H and J there is another char, #173 or &shy;, that doesn't show in FireFox or Chrome. But IE users can see it here:

 string chars = "abcdefghijkmnopqrstuvwxyzABCDEFGH­JKLMNOPQRSTUVWXYZ123456789";

So, to solve it quickly just retype the HJK part of chars.

Upvotes: 6

Jon Skeet
Jon Skeet

Reputation: 1502716

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);
}

Upvotes: 8

Related Questions