简体   繁体   English

下面两行代码有什么区别

[英]What is Difference Between Below Two Line Of Codes

i am not able to understand why we have to add "a"+randomtext.Next(0,26) for text我不明白为什么我们必须为文本添加"a"+randomtext.Next(0,26)

buffer[i] = (char)('a' + random.Next(0, 26));

versus相对

buffer[i] = (char)( random.Next(0, 26));

It is so you have all the letters of the alphabet.这样你就有了字母表中的所有字母。

When you pick a number between 0 and 25 and convert it to a char, you will end up with all kind of symbols in the ASCII-Table .当您选择 0 到 25 之间的数字并将其转换为字符时,您最终会在ASCII-Table 中得到所有类型的符号。

So you add the 'a' which is treated like an int (value is 97) to actually start at the correct position in the ascii-table.因此,您添加了被视为 int(值为 97)的 'a',以实际从 ascii 表中的正确位置开始。

So lets say you random 4.所以让我们说你随机 4。

This line这条线

(char)('a' + random.Next(0, 26));

will be将会

(char) ('a' + 4)
(char) (97 + 4)
(char) (101) => e

If you don't add 'a', you create an unprintable character.如果不添加 'a',则会创建一个不可打印的字符。 Value of 'a' + random value gives you a printable character 'a' 的值 + 随机值给你一个可打印的字符

You can look ASCII values at this link : http://www.asciitable.com/mobile/您可以在此链接中查看 ASCII 值: http : //www.asciitable.com/mobile/

The ASCII text encoding uses the lower 7 bits of a byte to encode characters. ASCII 文本编码使用字节的低 7 位对字符进行编码。 Not all of those characters are visible/printable (such as space, tab, newline, end-of-text, end-of-transmission, etc.).并非所有这些字符都是可见/可打印的(例如空格、制表符、换行符、文本结束符、传输结束符等)。

Lower case letters are encoded as values 0x61 ('a') through 0x7a ('z').小写字母编码为 0x61 ('a') 到 0x7a ('z') 的值。 By adding 'a' to your random value you guarantee that you will get one of the lower-case letters.通过将“a”添加到您的随机值,您可以保证您将获得小写字母之一。 Otherwise you would only get non-printable characters.否则你只会得到不可打印的字符。

Obviously there are issues with this code re 118n but ignoring that for now …很明显,这个代码是 118n 有问题,但现在忽略它……

The simple answer to why 'a' was added is to change the range of values placed into the buffer.添加“a”的简单答案是更改放入缓冲区的值的范围。

The same result may have been accomplished by simply adjusting the two values in the call to random.Next(97,123) etc. but in the interest of making the code understandable, adding the 'a' makes it more obvious what the acceptable range of values was that the coder intended to add to the buffer.通过简单地将调用中的两个值调整为 random.Next(97,123) 等,可能已经实现了相同的结果,但为了使代码易于理解,添加“a”使可接受的值范围更加明显是编码器打算添加到缓冲区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM