I am trying to learn C#. I already know Python. I wanted to replicate a simple password generator program I wrote in Python with C#. My problem is I don't know how to join the characters together into one string so I can display it. When I try to display it I just get blank spaces where the characters from the password should be.
In Python I can do this
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);
}
}
public class Rand
{
private static Random Generator = new Random();
public static Char RandChar(string items) //Choose a random char from string
{
int myIndex = Generator.Next(items.Length);
char l = items[myIndex];
return l;
}
public static string RandString(string[] items)//Choose a random string from a list
{
int myIndex = Generator.Next(items.Length);
string s = items[myIndex];
return s;
}
}
}
When I run the code I call Console.WriteLine(PasswordGenerator.Generate())
but It will not print my password. It will only print some commas and have blank spaces where the characters from the password should be. I need it to display my password. What am I doing wrong? How can I get it to display my password?
Append()function come from? Is it an extension method you defined? Otherwise, this code should not compile. Use aStringBuilderinstead of a char array. It has all the functions you are looking for.