C# 随机方法导致“隐藏破折号”
我正在尝试使用以下方法生成一个包含 8 个字符的随机字符串,它工作得很好,但这是一个小问题。
当我将字符串打印到屏幕并将其从 IE 复制到记事本时,有时会在字符串中间添加破折号 (-)。造成这种情况的原因是什么以及如何解决?
这种情况发生的次数并不多,也许只有 1/10 次,但它仍然会弄乱字符串。
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您显示的代码不会向字符串添加任何奇怪的内容。也许是您复制和粘贴的方式导致了问题。如果它偶尔会导致问题,请查看 HTML 源代码(右键单击“查看源代码”),看看是否可以在其中看到问题。
编辑:正如亨克发现的那样,您的代码显然并不像看上去的那样。你是如何在源代码中出现这个奇怪的字符的?
话虽如此,我肯定会更改您的代码的一些内容:
Random
作为参数,这样您就可以多次调用它快速连续而不多次生成相同的字符串只是为了让您了解它的样子 - 在这个示例中,我没有将字符集转换为参数,但我已从方法中提取了它:
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:
经过一番探索后,下面这行代码并不是看起来的那样。在字母 H 和 J 之间还有另一个字符 #173 或
,该字符在 FireFox 或 Chrome 中不显示。但 IE 用户可以在这里看到它:因此,要快速解决此问题,只需重新键入
chars
的 HJK 部分即可。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
, that doesn't show in FireFox or Chrome. But IE users can see it here:So, to solve it quickly just retype the HJK part of
chars
.