开发者

C# Random-method causes "hidden dash"

开发者 https://www.devze.com 2023-03-07 11:27 出处:网络
I\'m trying to generate a random str开发者_JAVA技巧ing with 8 characters with the following method and it works perfectly, but It\'s 1 little problem.

I'm trying to generate a random str开发者_JAVA技巧ing 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;
    }


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消