[英]What is the best way to compare 2 characters ignoring case in C#?
I am making password validation method using console app and got stuck with comparing two chars. 我正在使用控制台应用程序制作密码验证方法,并且无法比较两个字符。 Is there a way to compare two chars without using toUpper() or toLower( ) method.
有没有一种方法可以比较两个字符而无需使用toUpper()或toLower( )方法。 For example if i am comparing these two chars
例如,如果我正在比较这两个字符
char c1 = 'a', c2 = 'A';
bool result = c1.Equals(c2);
I want result to be true . 我希望结果是真实的 。
I've tried using toLower() method but i have a problem. 我试过使用toLower()方法,但是有问题。
This is my password validation Method. 这是我的密码验证方法。
private static bool PasswordValidation(string input)
{
if(!(input.Length>=8&&input.Length<=15))
{
Console.WriteLine("min 8 characters max 15");
return false;
}
int specialCharacters = 0, uppLatter = 0, lowerLatter = 0;
char[] charArray = input.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
char ch = charArray[i];
if (char.IsWhiteSpace(ch))
{
Console.WriteLine("can't use space in password");
return false;
}
if (!char.IsLetterOrDigit(ch))
specialCharacters++;
if (char.IsUpper(ch))
uppLatter++;
if (char.IsLower(ch))
lowerLatter++;
if (i < charArray.Length - 1)
{
if (char.ToLower(charArray[i])==char.ToLower(charArray[++i]))
{
Console.WriteLine("same characters");
return false;
}
if(char.IsDigit(charArray[i])&&char.IsDigit(charArray[++i]))
{
int sum = Convert.ToInt32(charArray[i]) + Convert.ToInt32(charArray[++i]);
if(sum==input.Length)
{
Console.WriteLine("sum is equal to length");
return false;
}
}
}
}
if (specialCharacters == 0)
{
Console.WriteLine("at lesast one special character is required");
return false;
}
if (uppLatter == 0)
{
Console.WriteLine("at lesast one upper latter is required");
return false;
}
if (lowerLatter == 0)
{
Console.WriteLine("at lesast one lower character is required");
return false;
}
var repeats = input.GroupBy(s1 => s1)
.Where(s1 => s1.Count() > 3)
.Select(s1 => s1).ToArray();
if (repeats.Length > 0)
{
Console.WriteLine("one character can't be repeted more than 3 times");
return false;
}
return true;
}
As you can see i've used integers to count the number of lower and upper letters, as well as special characters but this will only work for the first character of input string. 如您所见,我已经使用整数来计算低位和高位字母以及特殊字符的数量,但这仅适用于输入字符串的第一个字符。 Soon as i hit this
当我击中这个
if (char.ToLower(charArray[i])==char.ToLower(charArray[++i])) 如果(char.ToLower(charArray [i])== char.ToLower(charArray [++ i]))
line of code, all hell breaks loose. 的代码行,所有地狱打破。
Any suggestion is helpful. 任何建议都是有帮助的。 Thank you for your time.
感谢您的时间。
You can do this: 你可以这样做:
char c1 = 'a', c2 = 'A';
bool result = String.Equals(c1.ToString(), c2.ToString(), StringComparison.OrdinalIgnoreCase);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.