如何将数组中的字符串连接成一个字符串并将其显示在控制台中?

我正在努力学习C#。我已经了解Python。我想用 C# 复制我用 Python 编写的一个简单的密码生成器程序。我的问题是我不知道如何将字符连接到一个字符串中以便我可以显示它。当我尝试显示它时,我只是在密码字符应有的位置出现空格。


在Python中我可以做到这一点


password = []#will have random items appended by generator code

s = ''.join(password)#makes one string

print(s)#prints

namespace learning

{

    public static class PasswordGenerator

    {

        private static string Letters = "abcdefghijklmnopqrstuvwxyz";

        private static string Numbers = "1234567890";

        private static string Symbols = "!@#$%^&*()";


        public static string Generate()

        {

            string[] letters = new string[10];

            string[] choice = { "letter", "number", "symbol" };

            string[] UL = { "uper", "lower" };

            string get;

            char c;

            for (int i = 0; i <= 9; i++)

            {

                get = Rand.RandString(choice);

                if (get == "letter")

                {

                    c = Rand.RandChar(Letters);

                    get = Rand.RandString(UL);

                    if (get == "uper")

                    {

                        c = char.ToUpper(c);

                        letters.Append(c.ToString());

                    }

                    else

                    {

                        letters.Append(c.ToString());

                    }

                }

                if (get == "number")

                {

                    c = Rand.RandChar(Numbers);

                    letters.Append(c.ToString());

                }

                if (get == "symbol")

                {

                    c = Rand.RandChar(Symbols);

                    letters.Append(c.ToString());

                }

            }

            return String.Join(",", letters);

        }

    }

当我运行代码时,我调用Console.WriteLine(PasswordGenerator.Generate()) 但它不会打印我的密码。它只会打印一些逗号,并在密码中的字符应有的位置包含空格。我需要它来显示我的密码。我究竟做错了什么?我怎样才能让它显示我的密码?


梦里花落0921
浏览 157回答 3
3回答

有只小跳蛙

当您尝试letters.Append时,您正在尝试追加一个数组,这是不可能的,因为它是固定长度的。您可以使用List<String>,但在这种特殊情况下,您可以使用专门的 .Net 类,称为 StringBuilder。由于字符串是不可变的,因此在需要对字符串执行重复修改(例如向其附加值)的情况下,与创建新 String 对象相关的开销可能会很高。这就是 StringBuilder 发挥作用的地方。var letters = new StringBuilder();现在,您可以附加字符而无需进行 ToString() 转换。letters.Append(c)最后,要从 StringBuilder 返回字符串,可以使用 ToString 方法。return letters.ToString();

哆啦的时光机

要添加到其他答案中,您的 if 也有问题,它们应该是 if then else 或 switch如果您想保持正确的长度小重构使用迭代器方法和开关public static IEnumerable<char> Generate(int size, string[] choice, string[] ul){&nbsp; &nbsp;for (var i = 0; i < size; i++)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; switch (Rand.RandString(choice))&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case "letter":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (Rand.RandString(ul) == "uper")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield return char.ToUpper(Rand.RandChar(Letters));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield return Rand.RandChar(Letters);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case "number":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield return Rand.RandChar(Numbers);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case "symbol":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield return Rand.RandChar(Symbols);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}}用法string[] choice = { "letter", "number", "symbol" };string[] UL = { "uper", "lower" };Console.WriteLine(string.Concat(Generate(10, choice, UL)));演示在这里https://dotnetfiddle.net/qSHimm或者另一种方式public class Rand{&nbsp; &nbsp;private static Random Generator = new Random();&nbsp; &nbsp;public static T Get<T>(T[] items) //Choose a random char from string&nbsp; &nbsp; &nbsp; =>&nbsp; items[Generator.Next(items.Length)];}private static string Letters = "abcdefghijklmnopqrstuvwxyz";private static string Numbers = "1234567890";private static string Symbols = "!@#$%^&*()";public enum Options{&nbsp; &nbsp;Upper,Lower, Numbers, Symbols}public static IEnumerable<char> Generate(int size, params Options[] options){&nbsp; &nbsp;for (var i = 0; i < size; i++)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; switch (Rand.Get(options))&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case Options.Upper: yield return char.ToUpper(Rand.Get(Letters.ToCharArray())); break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case Options.Lower: yield return Rand.Get(Letters.ToCharArray()); break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case Options.Numbers: yield return Rand.Get(Numbers.ToCharArray()); break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;case Options.Symbols: yield return Rand.Get(Symbols.ToCharArray());break;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}}用法Console.WriteLine(string.Concat(Generate(10, Options.Upper,Options.Numbers)));输出R0P76UYO1D或者另一种方式public static string Generate(int size, params Options[] options)&nbsp; &nbsp;=> string.Concat(Enumerable.Repeat(0,size).Select(x => GetChar(options)));private static char GetChar(params Options[] options){&nbsp; &nbsp;switch (Rand.Get(options))&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; case Options.Upper:&nbsp; return char.ToUpper(Rand.Get(Letters.ToCharArray())); ;&nbsp; &nbsp; &nbsp; case Options.Lower: return Rand.Get(Letters.ToCharArray());&nbsp;&nbsp; &nbsp; &nbsp; case Options.Numbers:&nbsp; return Rand.Get(Numbers.ToCharArray());&nbsp;&nbsp; &nbsp; &nbsp; case Options.Symbols:&nbsp; return Rand.Get(Symbols.ToCharArray());&nbsp; &nbsp; &nbsp; default: throw new ArgumentOutOfRangeException();&nbsp; &nbsp;}}用法Console.WriteLine(Generate(10, Options.Upper,Options.Numbers));

胡说叔叔

对于生成随机密码来说,这看起来过于复杂。您可以使用下面的代码并使用可选参数(如果它们不向函数传递任何内容,则会生成长度为 15 的参数)。private static string CreateRandomPassword(int length = 15){    string validChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*?_-";    Random random = new Random();    // Select one random character at a time from the string      // and create an array of chars      char[] chars = new char[length];    for (int i = 0; i < length; i++)    {        chars[i] = validChars[random.Next(0, validChars.Length)];    }    return new string(chars);}
打开App,查看更多内容
随时随地看视频慕课网APP