C # Random method calls "hidden dash"

I am trying to create a random string with 8 characters with the following method and it works fine, but this is 1 small problem.

When I print a line on the screen and copy it from IE to Notepad, sometimes a dash (-) is added in the middle of the line. What causes this and how can I fix it?

This does not happen much, maybe 1/10 times, but still, it will ruin the line.

public string generateString() { int length = 8; string str = ""; string chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ123456789"; int charsCount = chars.Length; Random random = new Random(); for (int i = 0; i < length; i++) { str += chars[random.Next(0, charsCount)]; } return str; } 
+4
source share
2 answers

The code you specified will not add anything extra to the line. Perhaps this is how you copy and paste what causes the problem. If this sometimes causes a problem, look at the HTML source (right-click, “View Source”) and see if you see the problem there.

EDIT: As Henk found out, your code apparently doesn't seem so. How did you end up with a weird symbol in your source code?


Having said that, I would definitely change my code:

  • I would name this name according to the .NET naming conventions.
  • I would use Random as a parameter, so you can call it several times in a row without creating the same line several times
  • I would create a char array of the desired length, populate it, and then create a new string, instead of using string concatenation
  • I would create a string length to generate and possibly even character set options.

Just to give an idea of ​​how this would look: in this example, I did not turn the character set into a parameter, but I 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); } 
+8
source

After a little sneak, the next line is not what it seems. Between the letters H and J there is another char, # 173 or &shy; that does not appear in FireFox or Chrome. But IE users can see this here:

  string chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ123456789"; 

So, to quickly solve this problem, just enter the HJK part of the chars .

+6
source

All Articles