I came across article which explains how to do password strength validation.
I am having a problem with the errors I am encountering. One error states: Cannot implicitly convert type 'System.Text.RegularExpressions.Match' to 'bool' which is on line if (Regex.Match(password, #"/\d+/",...
The other error says: Operator '&&' cannot be applied to operands of type 'System.Text.RegularExpressions.Match' and 'System.Text.RegularExpressions.Match' which happens on line where AND or && statement is.
I don't understand why Regex statement isn't converting to bool type? And second problem is probably connected to the first one.
How can I fix this?
enum PasswordScore
{
Blank = 0,
VeryWeak = 1,
Weak = 2,
Medium = 3,
Strong = 4,
VeryStrong = 5
}
private static PasswordScore CheckStrength(string password)
{
int score = 1;
if (password.Length < 1)
return PasswordScore.Blank;
if (password.Length < 4)
return PasswordScore.VeryWeak;
if (password.Length >= 8)
score++;
if (password.Length >= 12)
score++;
if (Regex.Match(password, #"/\d+/", RegexOptions.ECMAScript))
score++;
if (Regex.Match(password, #"/[a-z]/", RegexOptions.ECMAScript) &&
Regex.Match(password, #"/[A-Z]/", RegexOptions.ECMAScript))
score++;
if (Regex.Match(password, #"/.[!,#,#,$,%,^,&,*,?,_,~,-,£,(,)]/",
RegexOptions.ECMAScript))
score++;
return (PasswordScore)score;
}
You need to use IsMatch, not Match. IsMatch returns a bool, while Match returns a Match object which gives you more detail (captured groups, etc)
Regex.Match() returns a Match object, not a boolean. You probably want to check the match.Success property, i.e.
var result = Regex.Match(...);
if(result.Success)
score++;
If success is all you care about, then just use the Success property of Match:
if (Regex.Match(password, #"/\d+/", RegexOptions.ECMAScript).Success)
and:
if (Regex.Match(password, #"/[a-z]/", RegexOptions.ECMAScript).Success &&
Regex.Match(password, #"/[A-Z]/", RegexOptions.ECMAScript).Success)
Regex.Match returns a Match type. See this link for official documentation
You will want to change your code to:
if(Regex.Match(...).Success) {
...
}
Or something very similar.
Related
I have a rather complex issue that I'am unable to figure out.
I'm getting a set of string every 10 seconds from another process in which the first set has first 5 characters constant, next 3 are variable and can change. And then another set of string in which first 3 are variable and next 3 are constant.
I want to compare these values to a fixed string to check if the first 5 char matches in 1st set of string (ABCDE*** == ABCDEFGH) and ignore the last 3 variable characters while making sure the length is the same. Eg : if (ABCDE*** == ABCDEDEF) then condition is true, but if (ABCDE*** == ABCDDEFG) then the condition is false because the first 5 char is not same, also if (ABCDE*** == ABCDEFV) the condition should be false as one char is missing.
I'm using the * in fixed string to try to make the length same while comparing.
Does this solve your requirements?
private static bool MatchesPattern(string input)
{
const string fixedString = "ABCDExyz";
return fixedString.Length == input.Length && fixedString.Substring(0, 5).Equals(input.Substring(0, 5));
}
In last versions of C# you can also use ranges:
private static bool MatchesPattern(string input)
{
const string fixedString = "ABCDExyz";
return fixedString.Length == input.Length && fixedString[..5].Equals(input[..5]);
}
See this fiddle.
BTW: You could probably achieve the same using regex.
It's always a good idea to make an abstraction. Here I've made a simple function that takes the pattern and the value and makes a check:
bool PatternMatches(string pattern, string value)
{
// The null string doesn't match any pattern
if (value == null)
{
return false;
}
// If the value has a different length than the pattern, it doesn't match.
if (pattern.Length != value.Length)
{
return false;
}
// If both strings are zero-length, it's considered a match
bool result = true;
// Check every character against the pattern
for (int i = 0; i< pattern.Length; i++)
{
// Logical and the result, * matches everything
result&= (pattern[i]== '*') ? true: value[i] == pattern[i];
}
return result;
}
You can then call it like this:
bool b1 = PatternMatches("ABCDE***", "ABCDEFGH");
bool b2 = PatternMatches("ABC***", "ABCDEF");
You could use regular expressions, but this is fairly readable, RegExes aren't always.
Here is a link to a dotnetfiddle: https://dotnetfiddle.net/4x1U1E
If the string you match against is known at compile time, your best bet is probably using regular expressions. In the first case, match against ^ABCDE...$. In the second case, match against ^...DEF$.
Another way, probably better if the match string is unknown, uses Length, StartsWith and EndsWith:
String prefix = "ABCDE";
if (str.Length == 8 && str.StartsWith(prefix)) {
// do something
}
Then similarly for the second case, but using EndsWith instead of StartsWith.
check this
public bool Comparing(string str1, string str2)
=> str2.StartWith(str1.replace("*","")) && str1.length == str2.Length;
I needed to implement a recursive method that checks whether an input is a palindrome or not. I was able to do this in one line and it works, but I'm not sure about how readable this is. I also keep getting a message "Simplify conditional ternary expression" but I'm not sure how
this is my code:
private static bool checkIfPalindrome(string i_InputToCheck, int i_StartIndex, int i_EndIndex)
{
return (i_StartIndex >= i_EndIndex) ? true : checkIfPalindrome(i_InputToCheck, i_StartIndex + 1, i_EndIndex - 1) && (i_InputToCheck[i_StartIndex] == i_InputToCheck[i_EndIndex]);
}
how readable this is
First off, naming convention: Get rid of unnecessary/uninformative parts of identifiers. For example, parameters do not need to start with i_ (presumably to denote “input”?). There’s no information conveyed here, and it adds noise. This has a huge impact on readability.
The logic itself can also be decluttered. The warning you’re getting gives you a hint that the condition can be simplified — this is always the case when your conditionals contain boolean literals.
More than anything, however, readability would benefit from breaking the expression up over multiple lines.
I would also swap the two secondary conditions, so that you first test the current characters, and then recurse further (only if the two currently tested characters are equal!):
private static bool IsPalindrome(string input, int start, int end) {
return (start >= end) ||
input[start] == input[end] &&
IsPalindrome(input, start + 1, end - 1);
}
This code relies on the correct precedence of && over ||. Some peope prefer making this operator precedence explicit by using more parentheses:
private static bool IsPalindrome(string input, int start, int end) {
return (start >= end) ||
(
input[start] == input[end] &&
IsPalindrome(input, start + 1, end - 1)
);
}
return i_StartIndex >= i_EndIndex || checkIfPalindrome(i_InputToCheck, i_StartIndex + 1, i_EndIndex - 1) && i_InputToCheck[i_StartIndex] == i_InputToCheck[i_EndIndex];
The simplification being prompted is because you're testing a boolean expression and then unnecessarily checking and returning it...
if (expression == true) is equivalent to if (expression) and
return expression ? true : false to return expression.
It is certainly not easy on the eye but I assume this is for a school exercise?
I have a fairly simple task which I want to do but something weird is happening. I just want to check if an element in a string equals zero and then set an integer accordingly.
This is my code
if (ssRow[(bar_position_row - 3)].Equals("0") && ssRow[(bar_position_row + 1)].Equals("0"))
{
back_row = 2;
front_row = 2;
}
else if (!ssRow[(bar_position_row - 3)].Equals("0") && !ssRow[(bar_position_row + 1)].Equals("0"))
{
back_row = 3;
front_row = 1;
}
else if (ssRow[(bar_position_row - 3)].Equals("0") && !ssRow[(bar_position_row + 1)].Equals("0"))
{
back_row = 2;
front_row = 1;
}
When I test my code, in several examples ssRow[(bar_position_row - 3)] and ssRow[(bar_position_row + 1)] equal zero but somehow the ssRow[(bar_position_row - 3)].Equals("0") and ssRow[(bar_position_row + 1)].Equals("0") are both FALSE. Does anyone know what my mistake is?
When you index into a string, what you get back is a char, not another string. You then compare this char to a string ("0"), and understandably get back false.
You should be comparing against '0' (a char), not "0" (a string). And since char is a value type, you can just use the == equality operator. If you had done so in the first place, this would have been a compile time error.
See example:
"abc"[0].Equals("a") //false
"abc"[0].Equals('a') //true
"abc"[0] == 'a' //true
"abc"[0] == "a" //compile-time error, can't compare char with string
I do not know the type of ssRow, if using index access on it does not return an string, then Equals("0") is doing object equality.
To fix it, consider using .ToString() first: ssRow[(bar_position_row - 3)].ToString().Equals("0")
I am making a pokemon game and this section is giving me 3 errors:
"Invalid expression term ';' (CS1525)" and "; expected(CS1002)"
public class HeldItem
{
public static int CritCalc(bool item,bool skill, bool UsedItem,int dmg)
{
Random rand=new Random();
Action jump=new Action();
int i = rand()%100;
double CritPerc = 6.25;
if(item==true)
CritPerc=12.5;
else if(skill==true)
CritPerc=12.5;
else if(UsedItem==true)
CritPerc=12.5;
else if((item==true & skill== true) || (item==true & UsedItem == true) || (skill==true & UsedItem==true))
CritPerc=25%;
else if(item==true & skill == true & UsedItem==true)
CritPerc=33.3%;
if(Action) //jump
CritPerc = 50%;
if(i<CritPerc)
dmg=2*dmg;
else if(i>CritPerc)
dmg==dmg;
return dmg;
}
}
}
Maybe it is a silly problem but I don't know what it is
You cannot specify percents in C#.
You have the following lines:
CritPerc=25%;
CritPerc=33.3%;
CritPerc = 50%;
That is invalid (Percent indicates the modulo operator in C#).
Instead, you probably want to specify the values as double floating point values.
CritPerc=0.25;
CritPerc=0.333;
CritPerc = 0.50;
%(percent) operator in c# means modulo operation which takes two
operand. but you give one. So it gives error.
Instead of
CritPerc=25%;
write
CritPerc=.25;
or
CritPerc=25/100;
and
dmg==dmg
causes error.
The line that says:
dmg == dmg;
Ah, the fatal '=' error.
You have dmg ==dmg which is the wrong operator and if dmg already has the correct value just return it, dmg=dmg goes without saying
How can I determine which string is before another if ordered alphabetically?
Examples:
is "add" before "ask"? true
is "aaaabba" before "aaac"? true
is "xeon" before "alphabet"? false
Is there something in .NET that can do this? Or does someone know of a good method to do this? Thanks in advance. I am using C#, but another language is fine for examples, or even pseudocode, or an idea, thanks.
You could use the Compare static method or CompareTo instance method:
class Program
{
static void Main()
{
Console.WriteLine(string.Compare("add", "ask") < 0);
Console.WriteLine(string.Compare("aaaabba", "aaac") < 0);
Console.WriteLine(string.Compare("xeon", "alphabet") < 0);
}
}
Prints:
True
True
False
Cation at comparing culture-aware strings !
String s1 = "Strasse";
String s2 = "Straße";
var res = String.Compare(s1, s2, StringComparison.Ordinal) == 0; // returns false
CultureInfo ci = new CultureInfo("de-DE");
eq = String.Compare(s1, s2, true, ci) == 0; // returns true
Use string.Compare method
static void Main(string[] args)
{
Console.WriteLine(
"is 'add' before 'ask'? {0}",
string.Compare("add", "ask") < 0
);
Console.WriteLine(
"is 'aaaabba' before 'aaac'? {0}",
string.Compare("aaaabba", "aaac") < 0
);
Console.WriteLine(
"is 'xeon' before 'alphabet'? {0}",
string.Compare("xeon", "alphabet") < 0
);
Console.ReadLine();
}
Use the StringComparer class
http://msdn.microsoft.com/en-us/library/system.stringcomparer.aspx
You can just use
int result = String.Compare(stringa, stringb);
If result > 0, then stringa would be before stringb, < 0 stringb before stringa and 0 for when they are the same.
string.Compare is the function you're looking for.
If the result is greater than 0, then the first argument is greater than the second one. If it's lower than 0 then it's the second one. If the function returns 0, then both arguments are equal.
If you are using some container then you can check index value to check this is it index before or not like this:
if( Array.IndexOf(strArray, "C") < Array.IndexOf(strArray, "C") ) return true;
As you know it is Ordered according to alphabet then you can use String.Compare Method (String, String)
retun string.Compare(string1, string2) < 0 ? true : false
The comparison uses the current culture to obtain culture-specific information such as casing rules and the alphabetic order of individual characters. For example, a culture could specify that certain combinations of characters be treated as a single character, or uppercase and lowercase characters be compared in a particular way, or that the sorting order of a character depends on the characters that precede or follow it.
When comparing strings, you should call the Compare method, which requires that you explicitly specify the type of string comparison that the method uses. For more information, see Best Practices for Using Strings in the .NET Framework.