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

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


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

        if (choice == 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]);
                }
            
            }
        }

        if (choice == 2)

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

        if (choice == 3)

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

        if (choice == 4)

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

        if (choice == 5)

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

        if (choice == 6)

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

        if (choice == 7)

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

        if (choice == 8)

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

        return sb.ToString();
    }

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


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


        
        string password = GetRandomPassword(length);
        Console.WriteLine(password);
        
    }
} ``` 
3
  • В коллекцию добавляйте каждую строку и всё, потом можно будет склеить элементы в строку каким-нибудь string.Join 17 фев 2022 в 6:56
  • @Aarnihauta Зачем такие сложности? Почитайте доки по SB.
    – aepot
    17 фев 2022 в 7:18
  • @aepot видимо вопрос неправильно понял 17 фев 2022 в 7:20

2 ответа 2

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

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

    string result = "";

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

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

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

    return "";
}
1
  • 1
    Спасибо огромное!
    – foder.
    17 фев 2022 в 7:54
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("Выберите тип паролей: ");
        Console.WriteLine("1) Цифры ");
        Console.WriteLine("2) Анг + Рус алфавиты в нижнем регистре ");
        Console.WriteLine("3) Анг алфавит в нижнем регистре ");
        Console.WriteLine("4) Рус алфавит в нижнем регистре ");
        Console.WriteLine("5) Анг + Рус алфавиты в верхнем регистре ");
        Console.WriteLine("6) Анг алфавит в верхнем регистре ");
        Console.WriteLine("7) Рус алфавит в верхнем регистре ");
        Console.WriteLine("8) Специальные символы ");
        int choice = Convert.ToInt32(Console.ReadLine());

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


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

        if (choice == 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.Append('\n');
            
            }
        }

        if (choice == 2)

        {
            for (int i = 0; i < amount; i++)
            {
                for (int n = 0; n < 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 < amount; i++)
            {
                for (int n = 0; n < length; n++)
                {
                    int index = rnd.Next(smalleng.Length);
                    sb.Append(smalleng[index]);
                }
            }
        }

        if (choice == 4)

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

        if (choice == 5)

        {
            for (int i = 0; i < amount; i++)
            {
                for (int n = 0; n < 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 < amount; i++)
            {
                for (int n = 0; n < length; n++)
                {
                    int index = rnd.Next(capitaleng.Length);
                    sb.Append(capitaleng[index]);
                }
                sb.Append('\n');
            }
        }

        if (choice == 7)

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

        if (choice == 8)

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

        return sb.ToString();
    }

    public static void Main()
    {
        Console.Write("Длина паролей = ");
        int length = Convert.ToInt32(Console.ReadLine());
        while (length < 6)
        {
            Console.WriteLine("Длина паролей должна быть больше либо равна 6! Введите значение заново"); 
            Console.Write("Длина паролей = ");
            length = Convert.ToInt32(Console.ReadLine());
        }
        
        string password = GetRandomPassword(length);
        Console.WriteLine(password);
        
    }
}
2
  • 1
    Вот, о чем я и говорил, вы пропустили 3 вариант, забыли внести правку в код. Но обратите внимание, что если в \n сработает в консоли, то он не сработает например в текстбоксе Windorms, вместо \n используйте Environment.NewLine тогда точно не ошибетесь. Либо как я предложил .AppendLine();
    – aepot
    17 фев 2022 в 7:57
  • 1
    Посмотрите здесь "Безотказный ввод числа", там используется делегат (предикат), незнакомая вам пока сущность, но наглядно показано, как оно работает. Это поможет еще улучшить код.
    – aepot
    17 фев 2022 в 8:03

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.