Related
I'm working on a program in c# where I'm supposed to tell the user to insert random characters and then divide those random characters into letters and numbers and count how many i have of each.
anyone has any idea how to do so?
thanks!
ps: i'm new to c# and programming alltogether :)
You could use char.IsDigit or char.IsNumber to check if it's a "number"(digit):
string input = Console.ReadLine();
int digitCount = input.Count(char.IsDigit);
int letterCount = input.Length - digitCount;
You need to add using System.Linq to be able to use Enumerable.Count.
Since you now have asked for counting vowels. Vowels are a, e, i, o, u and their uppercase version. So you could use this method:
private static readonly HashSet<char> Vowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
public static bool IsVowel(char c) => Vowels.Contains(c);
and this code to count the vowels:
int vowelCount = input.Count(IsVowel);
If you don't just want to count them but show them to the user:
string vowelsInInput = new String(input.Where(IsVowel).ToArray());
string noVowels = new String(input.Where(c => !IsVowel(c)).ToArray());
which also gives you the count(for example vowelsInInput.Length).
Get the input and loop through every character within the string
string testStr = "abc123";
foreach (char c in testStr)
{
Console.WriteLine(c.ToString( ));
}
You can use a dictionary to count the number of times a letter appears.
char letter = //your letter;
var charFrequencies = new Dictionary<char, int>();
if (!charFrequencies.ContainsKey(letter)) {
charFrequencies.Add(letter, 1);
}
else {
charFrequencies[letter]++;
}
im trying to split a string into a chars(which i have semi done) and use each char to compare it to my dictionary full of random strings, and then add that chars value in the dictionary to a finished string. the problem is what its outputting- the chars are not in order.
ex: USER INPUT: "hello"---
ex: CONSOLE: "e"-"l"-"l"-"o"-"h"
thats what happens mostly. any answer as to how i can get it to spell it correctly in the console?
Code:
private void complete_text_Click(object sender, RoutedEventArgs e)
{
end_result = input_box.Text.ToString();
string end_translated_result = "";
for (int i = 0; i < ZENOX_LANGUAGE.Keys.Count; i ++)
{
foreach (char iq in end_result.ToCharArray())
{
if (iq.ToString().ToLower() == ZENOX_LANGUAGE.Keys.ElementAt(i).ToString().ToLower())
{
Console.WriteLine(iq);
end_translated_result += ZENOX_LANGUAGE.Values.ElementAt(i) + " ";
//Console.WriteLine("sender: " + sender.ToString() + " c: " + end_result[iq].ToString().ToLower() + " s:" + ZENOX_LANGUAGE.Keys.ElementAt(i));
Console.WriteLine("end translated result: " + end_result);
}
}
}
}
As it stands, the order of keys in your dictionary will influence the order that output appears, because you're doing:
foreach(var k in dictionary.Keys)
foreach(char c in someString)
if(c == k)
Console.Write(c)
And dictionary keys have no defined order.
Swapping the loops over will mean (as long as the dictionary has the key you're looking for, as it's a condition that leads to printing the char) that the output will appear in order of chars in the string..
..but I can't actually work out why you enumerate the keys and then run a loop looking for the character. I'd just loop over the string and use the char to index the dictionary if I was building some sort of translator map:
var map = new Dictionary<char, char>() {
{ 'h', 'Z' },
{ 'e', 'Y' },
{ 'l', 'X' },
{ 'o', 'W' }
};
var toTrans = "hello";
foreach(char c in toTrans)
Console.Write(map[c]);
This will print "ZYXXW" for an input of "hello";
If you're mapping chars to strings, with case insensitivity it's as simple as:
var map = new Dictionary<char, string>() {
{ 'h', "Z0" },
{ 'e', "Y0" },
{ 'l', "X0" },
{ 'o', "W0" }
};
var toTrans = "HelLO";
foreach(char c in toTrans)
Console.Write(map[Char.ToLower(c)]);
This will print "Z0Y0X0X0W0"
I need to convert the characters a, e, i, o, u in the user input string to the assigned symbols. Below is what I have so far.
School assignment
First prompt the user for the encrypted text string. Validate that this is not left blank. Send this text string into a custom method you will create that will decipher it. Once it is deciphered, return this text string to the main where you will output both the encrypted and decrypted strings.
To decipher the text string you must perform the following character replacements:
# = a
# = e
^ = i
* = o
+ = u
My current code
public static string Decipher (string code)
{
char[] array = code.ToCharArray();
for (int i = 0; i < code.Length; i++)
{
if (code.Contains("#") && code.Contains("#") && code.Contains("^") &&
code.Contains("*") && code.Contains("+"))
{
}
}
Every time you go through this for loop, it will evaluate true if the string contains #, #, ^, * and + anywhere in the string. So if your string is missing any of these symbols, your if statement will evaluate to false and nothing will happen.
Luckily you can simplify this pretty easily. One way you can do this is to convert your string to a char[] array and break your logic into multiple if-else statements, or a single switch statement, for example:
public static string Decipher (string code)
{
char[] codeArray = code.ToCharArray(); // convert your code string to a char[] array
for (int i = 0; i < codeArray.Length; i++)
{
switch (codeArray[i]) // Get the char at position i in the array
{
case '#': // if the character at i is '#'
codeArray[i] = 'a'; // Change the character at i to 'a'
break; // break out of the switch statement - we don't need to evaluate anything else
case '#': // if the character at i is '#'
codeArray[i] = 'e'; // Change the character at i to 'e'
break; // break out of the switch statement - we don't need to evaluate anything else
// repeat for everything else you need to replace!
}
}
return new String(codeArray); // Once you're all done, create a string from your deciphered array and return it
}
There are a bunch of different ways of doing it. Doing string concatenation in a loop (as shown by #Acex) is generally frowned upon; it spins out a lot of "garbage" and can slow things down. The Stringbuilder class is generally a better option. My code uses Stringbuilders (well, the same one over and over - I clear it in between).
Here are several ways of doing the same thing:
const string encoded = "H#ll*, H*w #r# y*+?";
//good old fashioned C-style/brute force:
var buf = new StringBuilder();
foreach (var c in encoded){
switch(c){
case '#':
buf.Append('a');
break;
case '#':
buf.Append('e');
break;
case '^':
buf.Append('i');
break;
case '*':
buf.Append('o');
break;
case '+':
buf.Append('u');
break;
default:
buf.Append(c);
break;
}
}
var result = buf.ToString();
//using a lookup table (easily extensible)
buf.Clear();
var decodeDict = new Dictionary<char, char>{
{'#', 'a'},
{'#', 'e'},
{'^', 'i'},
{'*', 'o'},
{'+', 'u'},
};
foreach (var c in encoded){
if (decodeDict.Keys.Contains(c)){
buf.Append(decodeDict[c]);
} else {
buf.Append(c);
}
}
result = buf.ToString();
//something completely different
//instead of iterating through the string, iterate through the decoding dictionary
buf.Clear();
var working = new StringBuilder(encoded.Length);
working.Append(encoded);
foreach (var pair in decodeDict){
working.Replace(pair.Key, pair.Value);
}
result = working.ToString();
In each case, result holds, well, the result. Put a breakpoint right after each result assignment and see what's happened.
I'm not providing a lot of comments, step through the code, look up the classes and figure out what I'm doing (you are the student, after all).
It's really as simple as doing this:
public static string Decipher(string code)
{
var map = new Dictionary<char, char>()
{
{ '#', 'a' },
{ '#', 'e' },
{ '^', 'i' },
{ '*', 'o' },
{ '+', 'u' },
};
char[] array = code.ToCharArray();
array = array.Select(x => map.ContainsKey(x) ? map[x] : x).ToArray();
return new string(array);
}
Now you can do this:
string cipher = "*+tp+t";
string plain = Decipher(cipher);
Console.WriteLine(cipher);
Console.WriteLine(plain);
This outputs:
*+tp+t
output
For the sake of alternative
And when you will be allowed to use existing methods.
you can write something like this:
private Dictionary<char, char> mapping = new Dictionary<char, char>()
{
{ '#', 'a' },
{ '#', 'e' },
{ '^', 'i' },
{ '*', 'o' },
{ '+', 'u' },
};
private string Decrypt(string encryptedString) =>
string.Concat(encryptedString.Select(s => mapping.ContainsKey(s) ? mapping[s] : s));
And usage:
string result = Decrypt(encryptedString);
References: DotNetFiddle Example
Is there a code to check if a character is a vowel or consonant? Some thing like char = IsVowel? Or need to hard code?
case ‘a’:
case ‘e’:
case ‘i’:
case ‘o’:
case ‘u’:
case ‘A’:
case ‘E’:
case ‘I’:
case ‘O’:
case ‘U’:
You could do this:
char c = ...
bool isVowel = "aeiouAEIOU".IndexOf(c) >= 0;
or this:
char c = ...
bool isVowel = "aeiou".IndexOf(c.ToString(), StringComparison.InvariantCultureIgnoreCase) >= 0;
Once you add international support for things like éèe̋ȅëêĕe̊æøи etc. this string will get long, but the basic solution is the same.
Here's a function that works:
public static class CharacterExtentions
{
public static bool IsVowel(this char c)
{
long x = (long)(char.ToUpper(c)) - 64;
if (x*x*x*x*x - 51*x*x*x*x + 914*x*x*x - 6894*x*x + 20205*x - 14175 == 0) return true;
else return false;
}
}
Use it like:
char c = 'a';
if (c.IsVowel()) { // it's a Vowel!!! }
(Yes, it really works, but obviously, this is a joke answer. Don't downvote me. or whatever.)
No. You need to define first what you regard as a vowel and as a consonant. For example, in English, “y” could be a consonant (as in “yes”) or a vowel (as in “by”). Letters like “é” and “ü” are probably vowels in all languages in which they are used, but it seems that you did not consider them at all. Primarily, you should define why you wish to classify letters as consonants and vowels.
Console.WriteLine("Please input a word or phrase:");
string userInput = Console.ReadLine().ToLower();
for (int i = 0; i < userInput.Length; i++)
{
//c stores the index of userinput and converts it to string so it is readable and the program wont bomb out.[i]means position of the character.
string c = userInput[i].ToString();
if ("aeiou".Contains(c))
{
vowelcount++;
}
}
Console.WriteLine(vowelcount);
The other methods given work. Here I am concerned with performance. For the two approaches I tested - using LINQ's Any method and using bit arithmetic, the use of bit arithmetic was more than ten times faster. Results:
Time for LINQ = 117 msec
Time for Bit masks = 8 msec
public static bool IsVowelLinq(char c)
{
char[] vowels = new[] { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
return vowels.Any(ch => ch == c);
}
private static int VowelMask = (1 << 1) | (1 << 5) | (1 << 9) | (1 << 15) | (1 << 21);
public static bool IsVowelBitArithmetic(char c)
{
// The OR with 0x20 lowercases the letters
// The test c > 64 rules out punctuation, digits, and control characters.
// An additional test would be required to eliminate characters above ASCII 127.
return (c > 64) && ((VowelMask & (1 << ((c | 0x20) % 32))) != 0);
}
See https://dotnetfiddle.net/WbPHU4 for the code in a test with timings.
The key idea with the bit mask is that the second bit is set for 'a', the sixth bit is set for 'e', etc. Then you take the letter, shift left by its ASCII value as an integer, and see if that bit in the mask is set. One bit is set in the mask for each vowel, and the OR operation performs the lowercasing of the letter first.
You can use "IsVowel" as you wanted. However the only thing is there is likely no default C# library or function that already does this out of the box, well if this is what you wanted. You will need to write a util method for this.
bool a = isVowel('A');//example method call
public bool isVowel(char charValue){
char[] vowelList = {'a', 'e', 'i', 'o', 'u'};
char casedChar = char.ToLower(charValue);//handle simple and capital vowels
foreach(char vowel in vowelList){
if(vowel == casedChar){
return true;
}
}
return false;
}
This works just fine.
public static void Main(string[] args)
{
int vowelsInString = 0;
int consonants = 0;
int lengthOfString;
char[] vowels = new char[5] { 'a', 'e', 'i', 'o', 'u' };
string ourString;
Console.WriteLine("Enter a sentence or a word");
ourString = Console.ReadLine();
ourString = ourString.ToLower();
foreach (char character in ourString)
{
for (int i = 0; i < vowels.Length; i++)
{
if (vowels[i] == character)
{
vowelsInString++;
}
}
}
lengthOfString = ourString.Count(c => !char.IsWhiteSpace(c)); //gets the length of the string without any whitespaces
consonants = lengthOfString - vowelsInString; //Well, you get the idea.
Console.WriteLine();
Console.WriteLine("Vowels in our string: " + vowelsInString);
Console.WriteLine("Consonants in our string " + consonants);
Console.ReadKey();
}
}
Why not create an array of the vowels/consonants and check if the value is in the array?
You can do something like this in.
private bool IsCharacterAVowel(char c)
{
string vowels = "aeiou";
return vowels.IndexOf(c.ToString(),StringComparison.InvariantCultureIgnoreCase) >= 0;
}
You can use the following extension method:
using System;
using System.Linq;
public static class CharExtentions
{
public static bool IsVowel(this char character)
{
return new[] {'a', 'e', 'i', 'o', 'u'}.Contains(char.ToLower(character));
}
}
Use it like:
'c'.IsVowel(); // Returns false
'a'.IsVowel(); // Returns true
return "aeiou".Any( c => c.Equals( Char.ToLowerInvariant( myChar ) ) );
Try this out:
char[] inputChars = Console.ReadLine().ToCharArray();
int vowels = 0;
int consonants = 0;
foreach (char c in inputChars)
{
if ("aeiou".Contains(c) || "AEIOU".Contains(c))
{
vowels++;
}
else
{
consonants++;
}
}
Console.WriteLine("Vowel count: {0} - Consonant count: {1}", vowels, consonants);
Console.ReadKey();
Look at this code to check for both Vowel and Consonant , C#
private static void Vowel(string value)
{
int vowel = 0;
foreach (var x in value.ToLower())
{
if (x.Equals('a') || x.Equals('e') || x.Equals('i') || x.Equals('o') || x.Equals('u'))
{
vowel += 1;
}
}
Console.WriteLine( vowel + " number of vowels");
}
private static void Consonant(string value)
{
int cont = 0;
foreach (var x in value.ToLower())
{
if (x > 'a' && x <= 'd' || x > 'e' && x < 'i' || x > 'j' && x < 'o' || x >= 'p' && x < 'u' || x > 'v' && x < 'z')
{
cont += 1;
}
}
Console.WriteLine(cont + " number of consonant");
}
I was wondering how I can generate a strong and secure password in C#.
I googled a little bit and saw this formula in Wikipedia, where L is the length of the password and N is the number of possible symbols:
Also, I've found this question, but for some reason the method Membership.GeneratePassword just returns a random number with 1 digit, which absolutely no password. All the rest solutions, were very slow (>= 0.5 secs).
I need help implementing this formula (I don't know where to start). You may also suggest another solution or explain why the GeneratePassword isn't working.
I just tried the following in linqpad:
System.Web.Security.Membership.GeneratePassword(25, 10)
This is the password I got:
[XTJ_67g.i/ag1rL)6_Yv>*+%
Or, if that's not secure enough, try this:
System.Web.Security.Membership.GeneratePassword(128, 100)
which got me the following when running it three times:
|c^.:?m)#q+(]V;}[Z(})/?-;$]+#!|^/8*_9.$&.&!(?=^!Wx?[#%+&-#b;)>N;&+*w[>$2+_$%l;+h+#zhs^{e?&=*(}X_%|:}]]}*X[+)Er%J/-=;Q0{:+=%c7:^$
/:_)hxF+*){2|;(>:*N^+!_&|}B.$})?[V=[+v({-:-#9-Z$j?.[-}(#MHx+}(}Mz_S(7#4}{..>#G|!+++{+C=|_}=+r^#&$0;L*|kz-;$++/N3$=}?;%&]]*/^#^!+
:*{]-x^$g{|?*))_=B#^.#%L;g|+)#[nq}?y(_(m;]S^I$*q=l-[_/?}&-!k^(+[_{Z|&:^%!_)!=p%=)=wYd-#.UP$%s1{*l%+[%?!c+7=#=.;{+M)!^}&d/]{];(&}
this took way less than a second, btw. The framework is your friend.
See http://msdn.microsoft.com/en-us/library/system.web.security.membership.generatepassword.aspx
Not sure where I found this but here's a class to generate high entropy, truly random strings that can be used as passwords.
using System.Security.Cryptography;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class PasswordGenerator
{
public int MinimumLengthPassword { get; private set; }
public int MaximumLengthPassword { get; private set; }
public int MinimumLowerCaseChars { get; private set; }
public int MinimumUpperCaseChars { get; private set; }
public int MinimumNumericChars { get; private set; }
public int MinimumSpecialChars { get; private set; }
public static string AllLowerCaseChars { get; private set; }
public static string AllUpperCaseChars { get; private set; }
public static string AllNumericChars { get; private set; }
public static string AllSpecialChars { get; private set; }
private readonly string _allAvailableChars;
private readonly RandomSecureVersion _randomSecure = new RandomSecureVersion();
private int _minimumNumberOfChars;
static PasswordGenerator()
{
// Define characters that are valid and reject ambiguous characters such as ilo, IO and 1 or 0
AllLowerCaseChars = GetCharRange('a', 'z', exclusiveChars: "ilo");
AllUpperCaseChars = GetCharRange('A', 'Z', exclusiveChars: "IO");
AllNumericChars = GetCharRange('2', '9');
AllSpecialChars = "!##%*()$?+-=";
}
public PasswordGenerator(
int minimumLengthPassword = 15,
int maximumLengthPassword = 20,
int minimumLowerCaseChars = 2,
int minimumUpperCaseChars = 2,
int minimumNumericChars = 2,
int minimumSpecialChars = 2)
{
if (minimumLengthPassword < 15)
{
throw new ArgumentException("The minimumlength is smaller than 15.",
"minimumLengthPassword");
}
if (minimumLengthPassword > maximumLengthPassword)
{
throw new ArgumentException("The minimumLength is bigger than the maximum length.",
"minimumLengthPassword");
}
if (minimumLowerCaseChars < 2)
{
throw new ArgumentException("The minimumLowerCase is smaller than 2.",
"minimumLowerCaseChars");
}
if (minimumUpperCaseChars < 2)
{
throw new ArgumentException("The minimumUpperCase is smaller than 2.",
"minimumUpperCaseChars");
}
if (minimumNumericChars < 2)
{
throw new ArgumentException("The minimumNumeric is smaller than 2.",
"minimumNumericChars");
}
if (minimumSpecialChars < 2)
{
throw new ArgumentException("The minimumSpecial is smaller than 2.",
"minimumSpecialChars");
}
_minimumNumberOfChars = minimumLowerCaseChars + minimumUpperCaseChars +
minimumNumericChars + minimumSpecialChars;
if (minimumLengthPassword < _minimumNumberOfChars)
{
throw new ArgumentException(
"The minimum length of the password is smaller than the sum " +
"of the minimum characters of all catagories.",
"maximumLengthPassword");
}
MinimumLengthPassword = minimumLengthPassword;
MaximumLengthPassword = maximumLengthPassword;
MinimumLowerCaseChars = minimumLowerCaseChars;
MinimumUpperCaseChars = minimumUpperCaseChars;
MinimumNumericChars = minimumNumericChars;
MinimumSpecialChars = minimumSpecialChars;
_allAvailableChars =
OnlyIfOneCharIsRequired(minimumLowerCaseChars, AllLowerCaseChars) +
OnlyIfOneCharIsRequired(minimumUpperCaseChars, AllUpperCaseChars) +
OnlyIfOneCharIsRequired(minimumNumericChars, AllNumericChars) +
OnlyIfOneCharIsRequired(minimumSpecialChars, AllSpecialChars);
}
private string OnlyIfOneCharIsRequired(int minimum, string allChars)
{
return minimum > 0 || _minimumNumberOfChars == 0 ? allChars : string.Empty;
}
public string Generate()
{
var lengthOfPassword = _randomSecure.Next(MinimumLengthPassword, MaximumLengthPassword);
// Get the required number of characters of each catagory and
// add random charactes of all catagories
var minimumChars = GetRandomString(AllLowerCaseChars, MinimumLowerCaseChars) +
GetRandomString(AllUpperCaseChars, MinimumUpperCaseChars) +
GetRandomString(AllNumericChars, MinimumNumericChars) +
GetRandomString(AllSpecialChars, MinimumSpecialChars);
var rest = GetRandomString(_allAvailableChars, lengthOfPassword - minimumChars.Length);
var unshuffeledResult = minimumChars + rest;
// Shuffle the result so the order of the characters are unpredictable
var result = unshuffeledResult.ShuffleTextSecure();
return result;
}
private string GetRandomString(string possibleChars, int lenght)
{
var result = string.Empty;
for (var position = 0; position < lenght; position++)
{
var index = _randomSecure.Next(possibleChars.Length);
result += possibleChars[index];
}
return result;
}
private static string GetCharRange(char minimum, char maximum, string exclusiveChars = "")
{
var result = string.Empty;
for (char value = minimum; value <= maximum; value++)
{
result += value;
}
if (!string.IsNullOrEmpty(exclusiveChars))
{
var inclusiveChars = result.Except(exclusiveChars).ToArray();
result = new string(inclusiveChars);
}
return result;
}
}
internal static class Extensions
{
private static readonly Lazy<RandomSecureVersion> RandomSecure =
new Lazy<RandomSecureVersion>(() => new RandomSecureVersion());
public static IEnumerable<T> ShuffleSecure<T>(this IEnumerable<T> source)
{
var sourceArray = source.ToArray();
for (int counter = 0; counter < sourceArray.Length; counter++)
{
int randomIndex = RandomSecure.Value.Next(counter, sourceArray.Length);
yield return sourceArray[randomIndex];
sourceArray[randomIndex] = sourceArray[counter];
}
}
public static string ShuffleTextSecure(this string source)
{
var shuffeldChars = source.ShuffleSecure().ToArray();
return new string(shuffeldChars);
}
}
internal class RandomSecureVersion
{
//Never ever ever never use Random() in the generation of anything that requires true security/randomness
//and high entropy or I will hunt you down with a pitchfork!! Only RNGCryptoServiceProvider() is safe.
private readonly RNGCryptoServiceProvider _rngProvider = new RNGCryptoServiceProvider();
public int Next()
{
var randomBuffer = new byte[4];
_rngProvider.GetBytes(randomBuffer);
var result = BitConverter.ToInt32(randomBuffer, 0);
return result;
}
public int Next(int maximumValue)
{
// Do not use Next() % maximumValue because the distribution is not OK
return Next(0, maximumValue);
}
public int Next(int minimumValue, int maximumValue)
{
var seed = Next();
// Generate uniformly distributed random integers within a given range.
return new Random(seed).Next(minimumValue, maximumValue);
}
}
Consume in your code thusly:
var generator = new PasswordGenerator();
string password = generator.Generate();
Console.WriteLine(password);
To address your question about that formula:
The formula is saying that a password of length L drawn from an alphabet of N symbols is equivalent to a password of length H drawn from an alphabet of two symbols. So if you have, say, 64 symbols (say abc...xyzABC...XYZ01...89_!) and the password is 10 characters long, then that gives you equivalent security to a password 10 log2 64 = 60 characters long drawn from the alphabet "ab".
A "log" is the inverse operation of exponentiation. Two to the sixth power gives you sixty-four, therefore the "log two" of sixty-four gives you six.
I don't know if this will help you, but this is what I use when I want to generate a random password which is also strong. It's quick and simple to implement/understand and isn't as much of an overkill as the one through the membership provider above...
private string Token(byte Length) {
char[] Chars = new char[] {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
};
string String = string.Empty;
Random Random = new Random();
for (byte a = 0; a < Length; a++) {
String += Chars[Random.Next(0, 61)];
};
return (String);
}
Why not just fill an array with some characters and pick on random a number of them. You can divide them in groups to be sure that are include letters numbers and special characters.
You will also have to pick a proper length and how much of every group of characters to include and that's it. I don't think you need some sophisticated formulas.
For systems that don't allow user-generated passwords it's very easy, actually: Any password is as secure as it's long. Not counting, of course, people who tack post-its to monitors, etc.
You probably want to maximize the set of characters from which the password is generated. But restricting the generated passwords greatly reduces the search space and therefore makes the password less secure. Again, this only holds if the user can't choose their own password.
If you deal with both generated and user-created passwords, then all bets are off, obviously. You then probably want to generate the passwords in a way that it uses as many characters from different classes as possible, resembling a strong user-chosen password. Ideally it should conform to the same constraints that the user-created password has to pass as well (if any).
I used random string from characters like below
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789&?%$#";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[Random.Next(s.Length)]).ToArray());
}