随机字符串生成器 [英] Random String Generator

查看:82
本文介绍了随机字符串生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我回来了一个新问题。



我正在开发一个名字&密码生成器,因为我似乎总是有一个问题,提出名称&一旦我这样做,我永远不会保存它们。

我将把它作为我在没有做任何其他项目时工作的主要项目。



这是基本的想法



1)。你按一下按钮&它会生成随机字符串(名称和密码。)

2)。如果你不喜欢那个名字&密码,您可以按一个新按钮生成一个新按钮。

2)。如果您对结果感到满意,可以按另一个按钮将其保存为txt文件。



这是基本的想法。

如前面提到的那样,我将把它作为一个主项目,所以我将继续研究它。尝试最终能够将密码加密到2048位密码。



--ISSUE--



所以,为了让我开始,我需要一些帮助,有一些代码片段,如果这是可能的我似乎有一个小问题创建随机字符串生成器本身,我尝试googleing的例子,但我只发现非常复杂的,我知道创建它应该像一个字符串一样容易,比如



  string  rString =(  abcdefghijklmnopqrstuvwxyz); 



然后......这就是我大脑关闭的地方,如果有人能帮助我的话。请记住我不要求你给我写代码,我会喜欢一个代码片段或一些我可以学习这些东西的链接。



谢谢!

解决方案

BladeLogan问:



@Sergey Alexandrovich Kryukov您如何评价此代码?你有什么我可以比较的吗?

有几个问题:



你初始化只有一个的例子是好的System.Random 。但是,对于真正的随机性(这是伪随机数生成器),您需要种子算法中的随机值。我是这样做的:

随机r = 随机(System.DateTime.Now.Ticks。 GetHashCode()); 



另请参阅Microsoft代码示例:日期时间结构(系统) [ ^ ]。



你硬编码很糟糕某些事情为立即常数。例如,26(也是10)。这是不可支持的。如果您更改abc ...字符串怎么办?你需要计算这个字符串长度的26。想象一下如果您决定更改角色曲目会发生什么。你会如何支持它?此字符串也不必是硬编码的。例如,您可以从单个字符和所需长度的字符长度自动生成数组。更强大的方法是通过第一个非字母字符来打破这个范围。为此,您可以使用 System.Char.IsLetter

Char.IsLetter方法(系统) [ ^ ]。



到目前为止,这是你的问题中最糟糕的,硬编码,而且是不受支持的方式。硬编码10并不是那么糟糕,但它位于代码的中间。如果你需要一个常量,那么声明显式常量总是更好, const int ...



让我们走得更远。



随机字符串的生成正常工作。但这是一个单独的功能。您需要将其定义为单独的不同单元,类型或至少一种方法。 Random 的实例可以作为参数传递给此方法。将UI与代码的其他部分分开尤为重要。 RandomString 未封装。通常,您需要在紧凑的单元中隐藏随机生成所需的所有内容,该单元不提供对外部上下文的任何访问。顺便说一下,不要使用,而是使用 string.Empty 。不,它没有任何功能差异,但使用此只读字段将帮助您摆脱立即常量,将使您的代码更具可支持性 - 见上文。 />


更多...



此外,永远不要使用像 Form1 button1_Click 。遵循相当不错的Windows命名约定真的很棒。 永远不要使用设计师生成的名称。设计师不知道你的意图。这些名称不是设计为原样。当然,算法不可能生成语义敏感的名称。你应该注意这一点。您应该在使用名称时重命名所有内容。这也是关于代码的可维护性。如果你几个月后查看你的代码,你可能甚至不知道你刚才做了什么。



最后, randomString + = ...... 非常糟糕。 您不应该使用重复的字符串连接;这是低效的。原因是:字符串类型是不可变的。你甚至没有连接字符串。您每次都创建一个新的字符串实例。为什么?这是解决方案:而不是 immutable 字符串类型,使用其可变对应项,类 System.Text.StringBuilder

StringBuilder类(System.Text) [ ^ ]。



这是我此时可以发现的全部内容。如您所见,存在许多问题,其中一些问题非常严重。您需要对它们进行全面分析并了解要注意的事项。



还有一件事:您的帖子解决方案1并不是真正的解决方案。更糟糕的是,为什么你会自己接受这个解决方案?下次,使用 改善问题来发布此类问题作为问题的一部分



-SA


这对您来说是一个挑战, Logan:编写一个使用以下Enumeration的类,返回一个用户指定长度的字符串,使用此枚举中用户的内容类型选项组成:

  //   Enumeration.HasFlag需要.NET> = 4.0  
使用系统;
使用 System.Collections.Generic;
使用 System.Text;

命名空间 LogansRun_2015_1
{
[标志]
public enum RndStrType
{
UseAlphaLower = 0x2,
UseAlphaUpper = 0x4,
UseWhiteSpace = 0x8,
UseDigits = 0x10,
UseOtherCharacters = 0x20
}

// 你会写这个班级
public static class RndStringMaker
{
private static Random rnd = new Random(DateTime.Now.Millisecond);

public static string GetRndString(RndStrType rst, int slength)
{
StringBuilder result = new StringBuilder(slength);

foreach (RndStrType标志 Enum.GetValues( typeof (RndStrType)))
{
if (rst.HasFlag(flag))
{
// 供您编写
}
}

for int i = 0 ; i < slength; i ++)
{
// 供您编写
}

return result.ToString();
}
}
}

代码完成后;我想通过以下方式测试它:

  string  test1 = RndStrMaker.GetRndString(RndStrType.UseAlphaLower, 26 ); 
string test2 = RndStrMaker.GetRndString(RndStrType.UseAlphaUpper, 26 );
string test3 = RndStrMaker.GetRndString(RndStrType.UseWhiteSpace, 10 );
string test4 = RndStrMaker.GetRndString(RndStrType.UseOtherCharacters, 12 );
string test5 = RndStrMaker.GetRndString(RndStrType.UseDigits, 10 );

得到如下结果:

 abcdefghijklmnopqrstuvwxyz // UseAlphaLower 
ABCDEFGHIJKLMNOPQRSTUVWXYZ // UseAlphaUpper
\\\\ // UseWhiteSpace
!#


%(* +, - ./:;& lt; =& gt;& gt;?@ [\] ^ _ // UseOtherCharacters
0123456789 / / UseDigits

并且,如果这样使用:

  string  test6 = 
RndStrMaker.GetRndString(
RndStrType.UseAlphaUpper
| RndStrType.UseOtherCharacters
| RndStrType.UseDigits,
35 );

// 查看如下结果:
AKSIO4,T:< 8XV9 + > 1KR< _ZX4 @ V9R9U>>

So i'm back with a new question.

I am currently developing a name & password generator because I always seem to have a issue with coming up with names & once I do I never save them.
I will have it as my main project that I work on when im not doing any other projects.

This is the basic idea

1).You press a button & it generates random string (a name & password.)
2). If you dont like that name & password you can press a new button to generate a new one.
2).If you are happy with the outcome you can press another button to save it as a txt file.

That is the basic idea.
As mentioned earlier in the question I will have it as a main project so I will work on it & try to eventually be able to add an encryption to the password to probably a 2048 bit one.

--ISSUE--

So, to get me started I would need some help, with some sort of "Code snippet if that is possible" I seem to have a small issue creating the random string generator itself, I tried googleing for examples but I only found really complex ones, I know there should be as easy way creating it with like a string such as

string rString = ("abcdefghijklmnopqrstuvwxyz");


and then.. and this is where my brain shuts off, If anyone could help me. Keep in mind im not asking you to write me the code, I would love a code snippet or some links to where I can learn this stuff.

Thanks!

解决方案

BladeLogan asked:


@Sergey Alexandrovich Kryukov How would you rate this code? Do you have anything I can compare it with?

There are several problems:

It's good that you initialized only one instance of System.Random. But, for real randomness (this is pseudo-random number generator), you need to seed a random value in an algorithm. I do it this way:

Random r = new Random(System.DateTime.Now.Ticks.GetHashCode());


See also the Microsoft code sample: DateTime Structure (System)[^].

It's bad that you hard-coded certain things as immediate constants. For example, 26 (and also 10). This is not supportable. What if you change your "abc..." string? You need to calculate this 26 out of the length of this string. Imagine what happens if you decide to change character repertoire. How would you support it. This string, too, does not have to be hard-coded. You can, for example, auto-generate the array from, say, a single character, and required length of character length. More robust approach would be to break this range by first non-letter character. For that purpose, you can use System.Char.IsLetter:
Char.IsLetter Method (System)[^].

So far, this is the worst of your problem, hard-coding, and, moreover, in unsupportable way. Hard-coded 10 is not that bad, but it's in the middle of the code. If you need a constants, it's always better to declarer explicit constant, const int….

Let's go further.

Generation of random string works correctly. But this is a separate functionality. You need to defined it as a separate distinct unit, as type or at least a method. The instance of Random can be passed to this method as a parameter. It's is especially important to separate UI from other parts of code. RandomString is not encapsulated. Generally, you need to hide all you need for random generation in a compact unit which does not give any access to outside context. By the way, instead of "", always use string.Empty. No, it makes no functional difference, but using this readonly field will help you when you get rid of immediate constants, will make your code more supportable — see above.

Some more…

Also, never ever use names like Form1 and button1_Click. It's really good to follow pretty good Windows naming conventions. Never ever use names generated by the designer. The designers "does not know" your intentions. Those names are not designed to be left as is. And of course it's impossibly for the algorithm to generate semantically sensible name. You should take care about that. You should rename everything as you use the names. This is also about the maintainability of your code. If you look at your code few months later, you may not even understand what you did a while ago.

And finally, randomString += … is really bad. You should not use repeated string concatenation; this is inefficient. The reason is: string type is immutable. You don't even concatenate string. You create a new string instance every time. Why? Here is the solution: instead of immutable string type, use its mutable counterpart, the class System.Text.StringBuilder:
StringBuilder Class (System.Text)[^].

That's all I could spot by this time. As you can see, there are many problems, and some of them are serious enough. You need to analyze them all and learn what to pay attention for.

One more thing: your post "Solution 1" is not really a solution. Worse, why would you self-accept this "solution"? Next time, post such matter as a part of your question, using "Improve question".

—SA


Here's a challenge for you, Logan: write a Class that uses the following Enumeration to return a string with a length the user specifies, composed using the user's type-of-content choices from this Enumeration:

// Enumeration.HasFlag requires .NET >= 4.0
using System;
using System.Collections.Generic;
using System.Text;

namespace LogansRun_2015_1
{
    [Flags]
    public enum RndStrType
    {
       UseAlphaLower = 0x2,
       UseAlphaUpper = 0x4,
       UseWhiteSpace = 0x8,
       UseDigits = 0x10,
       UseOtherCharacters = 0x20
    }

    // you'll write this Class
    public static class RndStringMaker
    {
        private static Random rnd = new Random(DateTime.Now.Millisecond);

        public static string GetRndString(RndStrType rst, int slength)
        {
            StringBuilder result = new StringBuilder(slength);
     
            foreach (RndStrType flag in Enum.GetValues(typeof(RndStrType)))
            {
                if (rst.HasFlag(flag))
                {
                     // for you to write
                }
            }

            for (int i = 0; i < slength; i++)
            {
                // for you to write
            }

            return result.ToString();
        }
    }
}

When your code is complete; I want to see it tested with the following:

string test1 = RndStrMaker.GetRndString(RndStrType.UseAlphaLower, 26);
string test2 = RndStrMaker.GetRndString(RndStrType.UseAlphaUpper, 26);
string test3 = RndStrMaker.GetRndString(RndStrType.UseWhiteSpace, 10);
string test4 = RndStrMaker.GetRndString(RndStrType.UseOtherCharacters, 12);
string test5 = RndStrMaker.GetRndString(RndStrType.UseDigits, 10);

And get results like these:

abcdefghijklmnopqrstuvwxyz  //UseAlphaLower
ABCDEFGHIJKLMNOPQRSTUVWXYZ  //UseAlphaUpper
 \t\n\r // UseWhiteSpace
!#


%(*+,-./:;&lt;=&gt;&gt;?@[\]^_ // UseOtherCharacters 0123456789 // UseDigits

And, if used like this:

string test6 =
RndStrMaker.GetRndString(
    RndStrType.UseAlphaUpper 
    | RndStrType.UseOtherCharacters 
    | RndStrType.UseDigits, 
    35);

// see a result like this:
AKSIO4,T:<8XV9+>1KR<_ZX4@V9R9U>>


这篇关于随机字符串生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆