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 = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ123456789";
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:
Random
as a parameter, so you can call it multiple times in quick succession without generating the same string multiple timesJust 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With