用随机值替换字符串的最佳方法精确长度c#
我正在寻找用随机值替换字符串 - 并保持相同的长度。但是,我希望所有字符都替换为字符,数字都替换为数字。
我想知道做到这一点的最佳方法。我正在考虑对每个字符进行 for 循环,但这可能会非常消耗性能。
我可能是错的,在这种情况下请告诉我。
谢谢
I'm looking to replace a string with random values - and keep the same length. However, I'd like all characters to be replaced with chars, digits to be replaced with digits.
I'm wondering the best way to do this. I'm considering a for loop through each character but that could be potentially quite performance intensive.
I may be wrong, in which case please do let me know.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您错了。要知道它是字符还是数字,您需要查看字符串中的每个值,因此无论如何都需要循环遍历字符串。
You are wrong. To know whether it is a character or a digit, you need to look at each value in the string, so you need to loop over the string in any case.
除非您有性能要求和/或问题,否则不要进行微优化。只需使用一个循环即可。
Unless you've got a performance requirement and/or problem, don't micro-optimize. Just use a loop.
如果不循环遍历每个角色,你还能怎么做呢?至少,您需要查看该字符是否是数字并替换它。我假设您可以创建一个名为 RandomChar 和 RandomDigit 的函数。这将比 C# 风格更接近 C++ 风格,但你会明白:
确实没有其他方法,因为无论如何你都需要检查每个字符。
函数 isDigit、RandomDigit 和 RandomChar 留给读者作为练习。
How else are you going to do it without looping thorough each character? At a minimum, you need to look to see if the character is a digit or not and replace it. I'll assume you can make a function called RandomChar and RandomDigit. And this will be written more c++ ish than c# ish, but you get the idea:
There's really no other way since you need to inspect each character anyway.
the functions isDigit, RandomDigit, and RandomChar are left as exercises to the reader.
如果它是一个长字符串,则可能是因为对字符串的更改会导致创建新对象。我会使用 for 循环,但将字符串转换为 char 数组操作,然后再转换回字符串。
If it is a long string it can be since changes to a string cause a new object to be created. I would use a for loop but convert your string to a char array manipulate and then back to a string.
(我假设您已经有了生成随机字符的方法。)
(I have assumed you already have methods for generating random characters.)
考虑使用 LINQ 来帮助避免显式循环。您可以重构以确保数字
Consider using LINQ to help avoid explict loops. You can refactor to ensure that numbers