【问题标题】:Turn a string into password [closed]将字符串转换为密码[关闭]
【发布时间】:2018-03-25 18:34:21
【问题描述】:
static string ReadPassword(int length, char c)

该方法应允许您输入字符串作为密码。 length 是密码的最小长度,c 是屏幕上显示的每个密码数字的字符。

请输入至少 8 个字符的密码,以便在 Main 中使用:

string pwd = ReadPassword(8, '●')

用户键入他/她的密码字母。但是,屏幕上不会出现字母,而是存储在c中的字符,例如项目符号'●'。

我如何构建程序,即使我的方法以 return s; 结束,它也会为在控制台中键入的每个字符写入 *?

【问题讨论】:

  • 好的..但是..你忘了问一个问题!
  • 我真的不知道从哪里开始通过学习基础知识或/和开始研究?
  • "I dont really know where to begin" 要求您的导师澄清?
  • 你绝对不应该把你的作业外包给 Stack Overflow。

标签: c# string methods console passwords


【解决方案1】:

您可以将光标位置设置为输入位置或使用ReadKey(true)试试这个:

class Program
{
    static void Main(string[] args)
    {
        Console.Write("Set password: ");
        var password = ReadPassword(8, 'o');
        Console.WriteLine();
        Console.WriteLine($"Your password is: {password}");
        Console.ReadKey();
    }

    static string ReadPassword(int length, char c)
    {
        var left = Console.CursorLeft;
        var top = Console.CursorTop;
        var password = new StringBuilder();
        for (int i = 0; i < length; i++)
        {
            password.Append(Console.ReadKey().KeyChar);
            Console.SetCursorPosition(left + i, top);
            Console.Write(c);
        }
        return password.ToString();
    }
}

您可以在此处找到文档:https://msdn.microsoft.com/en-us/library/system.console.readkey(v=vs.110).aspx

【讨论】:

  • 这很有效,谢谢,我已经尝试了 2 个小时,但没有找到我需要的版本。感谢您的帮助!
【解决方案2】:

给你。

class Program {
        static void Main(string[] args) {
            char ch;int len;
            Console.WriteLine("Enter the Length of the Password: ");
            len = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter the Character for Password:");
            ch = Convert.ToChar(Console.Read());
            printPassword(len, ch);
            Console.Read();
        }
        public static void printPassword(int len,char ch) {
            char ch1;String pass="";
            int i;
            for (i = 0; i < len; i++) {
                pass += Console.ReadKey(true);
                Console.Write(ch);
            }
        }
    }

【讨论】:

  • 谢谢,请问您是如何得出这个答案的,因为更重要的是我作为一名学生能够自己解决这个问题。你会推荐任何关于 c# 的书吗?
  • Clean Code 来自 Martin 和 Adaptive Code 来自 Gary McLean Hall 是非常适合初学者的书籍。
  • @cSteusloff 谢谢你这么笨的人,你真是太好了。
  • msdn.microsoft.com/en-us/library/x3h8xffw(v=vs.110).aspx 检查此链接。从这里我来到了答案。我曾经将它用于我自己的控制台项目。
  • @PronoyMukherjee 谢谢伙计,解释得很好。出于某种原因,我因寻求帮助而受到了很多麻烦,我是新手,所以我不确定我是否做错了。很高兴得到一些有用的回复。
猜你喜欢
  • 1970-01-01
  • 2014-03-15
  • 2011-06-14
  • 2012-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多