1

Имеется такой генератор паролей. Но когда программа доходит до вывода количества полученных паролей, то они соединяются вместе. (Пример: программа сделала 2 пароля '123' и '321', но результат выходит, как '123321'). Как можно разделить эти пароли под каждую новую строку?

using System.Text;

public class Passgen { public static string GetRandomPassword(int length) { int amount = 0; const string digits = "0123456789"; const string smalleng = "abcdefghijklmnopqrstuvwxyz"; const string capitaleng = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const string smallrus = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"; const string capitalrus = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"; const string smalleng_smallrus = smalleng + smallrus; const string capitaleng_capitalrus = capitaleng + capitalrus; const string special = "!#$%&'()*+,-./:;<=>?@[\]^_'{|}~ ";

    Console.WriteLine(&quot;Выберите тип паролей: &quot;);
    Console.WriteLine(&quot;1) Цифры &quot;);
    Console.WriteLine(&quot;2) Анг + Рус алфавиты в нижнем регистре &quot;);
    Console.WriteLine(&quot;3) Анг алфавит в нижнем регистре &quot;);
    Console.WriteLine(&quot;4) Рус алфавит в нижнем регистре &quot;);
    Console.WriteLine(&quot;5) Анг + Рус алфавиты в верхнем регистре &quot;);
    Console.WriteLine(&quot;6) Анг алфавит в верхнем регистре &quot;);
    Console.WriteLine(&quot;7) Рус алфавит в верхнем регистре &quot;);
    Console.WriteLine(&quot;8) Специальные символы &quot;);
    int choice = Convert.ToInt32(Console.ReadLine());

    Console.Write(&quot;Количество паролей = &quot;);
    amount = int.Parse(Console.ReadLine());


    StringBuilder sb = new StringBuilder();
    Random rnd = new Random();

    if (choice == 1)

    {
        for (int i = 0; i &lt; amount; i++)
        {
            for (int n = 0; n &lt; length; n++)
            {
                int index = rnd.Next(digits.Length);
                sb.Append(digits[index]);
            }

        }
    }

    if (choice == 2)

    {
        for (int i = 0; i &lt; amount; i++)
        {
            for (int n = 0; n &lt; length; n++)
            {
                int index = rnd.Next(smalleng_smallrus.Length);
                sb.Append(smalleng_smallrus[index]);
            }
        }
    }

    if (choice == 3)

    {
        for (int i = 0; i &lt; amount; i++)
        {
            for (int n = 0; n &lt; length; n++)
            {
                int index = rnd.Next(smalleng.Length);
                sb.Append(smalleng[index]);
            }
        }
    }

    if (choice == 4)

    {
        for (int i = 0; i &lt; amount; i++)
        {
            for (int n = 0; n &lt; length; n++)
            {
                int index = rnd.Next(smallrus.Length);
                sb.Append(smallrus[index]);
            }
        }
    }

    if (choice == 5)

    {
        for (int i = 0; i &lt; amount; i++)
        {
            for (int n = 0; n &lt; length; n++)
            {
                int index = rnd.Next(capitaleng_capitalrus.Length);
                sb.Append(capitaleng_capitalrus[index]);
            }
        }
    }

    if (choice == 6)

    {
        for (int i = 0; i &lt; amount; i++)
        {
            for (int n = 0; n &lt; length; n++)
            {
                int index = rnd.Next(capitaleng.Length);
                sb.Append(capitaleng[index]);
            }
        }
    }

    if (choice == 7)

    {
        for (int i = 0; i &lt; amount; i++)
        {
            for (int n = 0; n &lt; length; n++)
            {
                int index = rnd.Next(capitalrus.Length);
                sb.Append(capitalrus[index]);
            }
        }
    }

    if (choice == 8)

    {
        for (int i = 0; i &lt; amount; i++)
        {
            for (int n = 0; n &lt; length; n++)
            {
                int index = rnd.Next(special.Length);
                sb.Append(special[index]);
            }
        }
    }

    return sb.ToString();
}

public static void Main()
{
    begin: Console.Write(&quot;Длина паролей = &quot;);
    int length = Convert.ToInt32(Console.ReadLine());


    if (length &lt; 6) { Console.WriteLine(&quot;Длина паролей должна быть больше либо равна 6! Введите значение заново&quot;); goto begin; }



    string password = GetRandomPassword(length);
    Console.WriteLine(password);

}

} ```

foder.
  • 47
  • В коллекцию добавляйте каждую строку и всё, потом можно будет склеить элементы в строку каким-нибудь string.Join – Aarnihauta Feb 17 '22 at 06:56
  • @Aarnihauta Зачем такие сложности? Почитайте доки по SB. – aepot Feb 17 '22 at 07:18
  • @aepot видимо вопрос неправильно понял – Aarnihauta Feb 17 '22 at 07:20

2 Answers2

1

Ответ на вопрос выглядит так

for (int i = 0; i < amount; i++)
{
    for (int n = 0; n < length; n++)
    {
        int index = rnd.Next(digits.Length);
        sb.Append(digits[index]);
    }
    sb.AppendLine();
}

Но у вас очень много повторяющегося кода. Обратите внимание на то, в скольких местах вам надо поправить код, чтобы внести предложенное мной решение в свой код? А должно быть в одном. Давайте исправим это.

Для начала, вынести генерацию пароля в отдельный метод, тогда код получится такой.

private static readonly Random rnd = new Random();

private static string GeneratePassword(string chars, int amount, int length) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < amount; i++) { for (int n = 0; n < length; n++) { int index = rnd.Next(chars.Length); sb.Append(chars[index]); } sb.AppendLine(); } return sb.ToString(); }

public static string GetRandomPassword(int length) { int amount = 0; const string digits = "0123456789"; const string smalleng = "abcdefghijklmnopqrstuvwxyz"; const string capitaleng = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const string smallrus = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"; const string capitalrus = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"; const string smalleng_smallrus = smalleng + smallrus; const string capitaleng_capitalrus = capitaleng + capitalrus; const string special = "!#$%&'()*+,-./:;<=>?@[\]^_'{|}~ ";

Console.WriteLine(&quot;Выберите тип паролей: &quot;);
Console.WriteLine(&quot;1) Цифры &quot;);
Console.WriteLine(&quot;2) Анг + Рус алфавиты в нижнем регистре &quot;);
Console.WriteLine(&quot;3) Анг алфавит в нижнем регистре &quot;);
Console.WriteLine(&quot;4) Рус алфавит в нижнем регистре &quot;);
Console.WriteLine(&quot;5) Анг + Рус алфавиты в верхнем регистре &quot;);
Console.WriteLine(&quot;6) Анг алфавит в верхнем регистре &quot;);
Console.WriteLine(&quot;7) Рус алфавит в верхнем регистре &quot;);
Console.WriteLine(&quot;8) Специальные символы &quot;);
int choice = Convert.ToInt32(Console.ReadLine());

Console.Write(&quot;Количество паролей = &quot;);
amount = int.Parse(Console.ReadLine());

string result = &quot;&quot;;

if (choice == 1)
{
    result = GeneratePassword(digits, amount, length);
}

if (choice == 2)
{
    result = GeneratePassword(smalleng_smallrus, amount, length);
}

if (choice == 3)
{
    result = GeneratePassword(smalleng, amount, length);
}

if (choice == 4)
{
    result = GeneratePassword(smallrus, amount, length);
}

if (choice == 5)
{
    result = GeneratePassword(capitaleng_capitalrus, amount, length);
}

if (choice == 6)
{
    result = GeneratePassword(capitaleng, amount, length);
}

if (choice == 7)
{
    result = GeneratePassword(capitalrus, amount, length);
}

if (choice == 8)
{
    result = GeneratePassword(special, amount, length);
}

return result;

}

Но все еще много повторяющегося кода, продолжим. Можно объединить константы в массив, тогда к константе можно будет обратиться по индексу в массиве, а не только по имени.

public static string GetRandomPassword(int length)
{
    const string digits = "0123456789";
    const string smalleng = "abcdefghijklmnopqrstuvwxyz";
    const string capitaleng = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const string smallrus = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
    const string capitalrus = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
    const string smalleng_smallrus = smalleng + smallrus;
    const string capitaleng_capitalrus = capitaleng + capitalrus;
    const string special = "!#$%&'()*+,-./:;<=>?@[\\]^_'{|}~ ";
string[] dictionaries = new string[]
{
    digits,
    smalleng,
    capitaleng,
    smallrus,
    capitalrus,
    smalleng_smallrus,
    capitaleng_capitalrus,
    special
};

Console.WriteLine(&quot;Выберите тип паролей: &quot;);
Console.WriteLine(&quot;1) Цифры &quot;);
Console.WriteLine(&quot;2) Анг + Рус алфавиты в нижнем регистре &quot;);
Console.WriteLine(&quot;3) Анг алфавит в нижнем регистре &quot;);
Console.WriteLine(&quot;4) Рус алфавит в нижнем регистре &quot;);
Console.WriteLine(&quot;5) Анг + Рус алфавиты в верхнем регистре &quot;);
Console.WriteLine(&quot;6) Анг алфавит в верхнем регистре &quot;);
Console.WriteLine(&quot;7) Рус алфавит в верхнем регистре &quot;);
Console.WriteLine(&quot;8) Специальные символы &quot;);
int choice = int.Parse(Console.ReadLine());

Console.Write(&quot;Количество паролей = &quot;);
int amount = int.Parse(Console.ReadLine());

if (choice &gt;= 1 &amp;&amp; choice &lt;= 8)
{
    return GeneratePassword(dictionaries[choice - 1], amount, length);
}

return &quot;&quot;;

}

aepot
  • 49,560
0

Вот еще один способ:

using System.Text;
using System;
public class Passgen
{
    public static string GetRandomPassword(int length)
    {
        int amount = 0;
        const string digits = "0123456789";
        const string smalleng = "abcdefghijklmnopqrstuvwxyz";
        const string capitaleng = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        const string smallrus = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
        const string capitalrus = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
        const string smalleng_smallrus = smalleng + smallrus;
        const string capitaleng_capitalrus = capitaleng + capitalrus;
        const string special = "!#$%&'()*+,-./:;<=>?@[\\]^_'{|}~ ";
    Console.WriteLine(&quot;Выберите тип паролей: &quot;);
    Console.WriteLine(&quot;1) Цифры &quot;);
    Console.WriteLine(&quot;2) Анг + Рус алфавиты в нижнем регистре &quot;);
    Console.WriteLine(&quot;3) Анг алфавит в нижнем регистре &quot;);
    Console.WriteLine(&quot;4) Рус алфавит в нижнем регистре &quot;);
    Console.WriteLine(&quot;5) Анг + Рус алфавиты в верхнем регистре &quot;);
    Console.WriteLine(&quot;6) Анг алфавит в верхнем регистре &quot;);
    Console.WriteLine(&quot;7) Рус алфавит в верхнем регистре &quot;);
    Console.WriteLine(&quot;8) Специальные символы &quot;);
    int choice = Convert.ToInt32(Console.ReadLine());

    Console.Write(&quot;Количество паролей = &quot;);
    amount = int.Parse(Console.ReadLine());


    StringBuilder sb = new StringBuilder();
    Random rnd = new Random();

    if (choice == 1)

    {
        for (int i = 0; i &lt; amount; i++)
        {
            for (int n = 0; n &lt; length; n++)
            {
                int index = rnd.Next(digits.Length);
                sb.Append(digits[index]);
            }
            sb.Append('\n');

        }
    }

    if (choice == 2)

    {
        for (int i = 0; i &lt; amount; i++)
        {
            for (int n = 0; n &lt; length; n++)
            {
                int index = rnd.Next(smalleng_smallrus.Length);
                sb.Append(smalleng_smallrus[index]);
            }
            sb.Append('\n');
        }
    }

    if (choice == 3)

    {
        for (int i = 0; i &lt; amount; i++)
        {
            for (int n = 0; n &lt; length; n++)
            {
                int index = rnd.Next(smalleng.Length);
                sb.Append(smalleng[index]);
            }
        }
    }

    if (choice == 4)

    {
        for (int i = 0; i &lt; amount; i++)
        {
            for (int n = 0; n &lt; length; n++)
            {
                int index = rnd.Next(smallrus.Length);
                sb.Append(smallrus[index]);
            }
            sb.Append('\n');
        }
    }

    if (choice == 5)

    {
        for (int i = 0; i &lt; amount; i++)
        {
            for (int n = 0; n &lt; length; n++)
            {
                int index = rnd.Next(capitaleng_capitalrus.Length);
                sb.Append(capitaleng_capitalrus[index]);
            }
            sb.Append('\n');
        }
    }

    if (choice == 6)

    {
        for (int i = 0; i &lt; amount; i++)
        {
            for (int n = 0; n &lt; length; n++)
            {
                int index = rnd.Next(capitaleng.Length);
                sb.Append(capitaleng[index]);
            }
            sb.Append('\n');
        }
    }

    if (choice == 7)

    {
        for (int i = 0; i &lt; amount; i++)
        {
            for (int n = 0; n &lt; length; n++)
            {
                int index = rnd.Next(capitalrus.Length);
                sb.Append(capitalrus[index]);
            }
            sb.Append('\n');
        }
    }

    if (choice == 8)

    {
        for (int i = 0; i &lt; amount; i++)
        {
            for (int n = 0; n &lt; length; n++)
            {
                int index = rnd.Next(special.Length);
                sb.Append(special[index]);
            }
            sb.Append('\n');
        }
    }

    return sb.ToString();
}

public static void Main()
{
    Console.Write(&quot;Длина паролей = &quot;);
    int length = Convert.ToInt32(Console.ReadLine());
    while (length &lt; 6)
    {
        Console.WriteLine(&quot;Длина паролей должна быть больше либо равна 6! Введите значение заново&quot;); 
        Console.Write(&quot;Длина паролей = &quot;);
        length = Convert.ToInt32(Console.ReadLine());
    }

    string password = GetRandomPassword(length);
    Console.WriteLine(password);

}

}

foder.
  • 47
  • 1
    Вот, о чем я и говорил, вы пропустили 3 вариант, забыли внести правку в код. Но обратите внимание, что если в \n сработает в консоли, то он не сработает например в текстбоксе Windorms, вместо \n используйте Environment.NewLine тогда точно не ошибетесь. Либо как я предложил .AppendLine(); – aepot Feb 17 '22 at 07:57
  • 1
    Посмотрите здесь "Безотказный ввод числа", там используется делегат (предикат), незнакомая вам пока сущность, но наглядно показано, как оно работает. Это поможет еще улучшить код. – aepot Feb 17 '22 at 08:03