Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Setting each character in a string to an asterisk (*) if a user has selected "Hidden" function

learning C# at the moment. Just wondering if it’s possible to set all the characters in a string to an asterisk symbol if a user has selected to hide the visibility of a password. Here is what I have so far:

private string Password
{ get; set; }

public bool Hidden
{ get; private set; }

public PasswordManager(string password, bool hidden)
{
  Password = password;
  Hidden = hidden;
}
public void Display()
{
  if (Hidden == false)
  {
    Console.WriteLine(password);
  }
  else if (Hidden == true)
  {
    Console.WriteLine("*");
  }
}

As you can see, if the Hidden bool is true, the Console.WriteLine needs to write the asterisk but I’d like it to write an asterisk for each character. Would it be possible to do something like a foreach loop not for string contents but rather for the characters in a given string. Using something like string.Length? Any assistance would be greatly appreciated. Thank you for your time!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the for loop to print each character as *:

public void Display()   
{
   if (Hidden == false)
   {
        Console.WriteLine(password);
   }
   else if (Hidden == true)
   {
       //Console.WriteLine("*");
       for(int i=0; i<password.Length;i++)
            Console.Write('*');
   }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading