How to check if two string are of the same length? - c#

I want to check if two string are of the same length. I tried the following, but it doesn't work.
string passnew = "1233";
string passcnfrm = "1234";
if((passnew.Length&&passcnfrm.Length)>6 ||(passnew.Length&&passcnfrm.Length)<15)
{
// ...
}
Why does it not work? What do I need to change?

if(passnew.Length == passcnfrm.Length &&
passnew.Length > 6 && passnew.Length < 15)
{
// do stuff
}

You are missing some basic syntax lessons. What you write inside of these brackets are conditions. We have unary operators (operating on one thing), binary operators (two) and one tertiary operator (forget about that one).
You cannot construct something like your "boundary test" with those easily.
A possible way:
(passnew.Length > 6) && (passcnfrm.Length > 6)
But you aren't testing if the length is equal anyway, even if you could use a syntax like that. You seem to want to compare if both are longer than 6 chars and shorter than 15 chars. One at 7 and one at 14 would satisfy both conditions..

if(passnew.Length == passcnfrm.Length &&
(passnew.Length < 15 && passnew.Length > 6))
{
// ...
}
Checks both are same length, and either one is more than 6 and less than 15 characters long.

that would be:
if(passcnfrm.Length.Equals(passnew.Length))
{
//do stuff
}

A probably better way to do it is:
if (( passnew != null && passcnfrm != null )
( passnew == passcnfrm )
&& ( passnew.Length > 6 && passnew.Length < 15 ))
{
// do stuff
}
Hides the length check inside the equality check which you'll probably need, it isn't in your question but the variable names make it pretty clear you're doing a password change function there. I added the null check to make sure the length checks don't throw a NullReferenceException, not needed in the example because you assign both manually, but might save some trouble if you're going to convert this to a method later on.

You can use like this:
if (s.Contains(s1[i]))
or:
boolean equalsIgnoreCase(String anotherString);
or use this method:
public static int occurrence(string [] a, string a2)
{
int occ = 0;
for (int i = 0; i < a.Length;i++ )
{
if(a[i].Equals(a2))
{
occ++;
}
}
return occ;
}

Related

What does the bracket in this expression mean

I am modifying another developer's code and I don't know what the [0] bracket following the string means in this context, can someone explain to me? My first thought is it is referring to the first column of GridView1 but that isn't the correct way to designate a column is it? BTW the string values in the if statement are 7 digit numbers expressed as strings. The first column is the DataKey column.
if (GridView1.SelectedValue.ToString()[0] != '5' && GridView1.SelectedValue.ToString().Substring(0, 2) != "95")
{
LinkButton1.Visible = false;
LinkButton2.Visible = false;
}
else
{
LinkButton1.Visible = true;
LinkButton2.Visible = true;
}
String Accessing Individual Characters
You can use array notation with an index value to acquire read-only
access to individual characters
if (GridView1.SelectedValue.ToString()[0] != '5' && GridView1.SelectedValue.ToString().Substring(0, 2) != "95")
As noted in the comments, both the below will throw if there are not enough characters
GridView1.SelectedValue.ToString()[0]
GridView1.SelectedValue.ToString().Substring(0, 2)
Also as per DRY calling this twice is redundant and also messy
GridView1.SelectedValue.ToString()
When you can
var something = GridView1.SelectedValue.ToString();
Lastly, normally you would check this for sanity sake, Like
if(!string.IsNullOrEmpty(something) && something.Length >= 2)
if (something[0] != '5' && something.Substring(0, 2) != "95")
Anyway, have fun stringing

Compare multiple values in one condition [duplicate]

This question already has answers here:
Equality comparison between multiple variables
(14 answers)
Closed 7 years ago.
Int32 int1, int2, int3 = 123;
Given the above variables, how can I test that all of my variables have the value 123 without creating a collection to perform some Any or something on?
What I've Tried
if(int1 == int2 == int3 == 123)
{
// Fantastic code here
}
EDIT
I must apologise, I haven't been clear enough in my question. I'm fully aware of the && operator, I was asking with regard to 'elegance', i.e. how can I avoid repeating the value I want to compare against.
In the same way I have assigned all 3 integer variables the same value in one hit, I'd like to now make the comparison. It's looking as though there is no way of doing this, so far. I think I'm asking the impossible, I'll have to stick to the basic syntax and keep it simple.
You can create an usefull extension function:
public static bool EqualsAll<T>(this T val, params T[] values)
{
return values.All(v => v.Equals(val));
}
call it like:
bool res = 123.EqualsAll(int1,int2,int3);
You could try something like this, using the logical and operator:
if(int1 == 123 &&
int2 == 123 &&
int3 == 123)
{
}
if(int1 == 123 && int2 == 123 && int3 == 123) { // Code }
What your trying to achieve isn't possible the way you do it.
You have to separate it with &.
if(int1 == something && int2 == something && int3 == 123)
{
// Fantastic code here
}
This is how you should do it using && operator. You can check multiple conditions using this.
UPDATE :
As far as checking multiple values at one go is concerned, you can try making an array out those values and just fire a simple LINQ statement like this to check all of them for a particular value :
if (new[] { int1, int2, int3 }.All(x => x == 1))
Dont know if this fits into your requirement, just a suggestion though.

How to handle Index out of range in a better way

My code was giving me Index out of Range exception for a certain input. Below is the problematic code:
string[] snippetElements = magic_string.Split('^');
string a = snippetElements[10] == null ? "" : "hello";
string b = snippetElements[11] == null ? "" : "world";
For that particular input, array snippetElements had only one element in it, hence while trying to index 10th and 11th element, I got the exception.
For now, I have introduced the following check:
if (snippetElements.Length >= 11)
{
string a = snippetElements[10] == null ? "" : "hello";
string b = snippetElements[11] == null ? "" : "world";
}
Can someone suggest a better way to write this check. Somehow the number 11 is not looking good in the code.
Yes this is an old post, but still helpful. You could use this which I think is cleaner:
string a = snippetElements.ElementAtOrDefault(10) ?? "hello";
string b = snippetElements.ElementAtOrDefault(11) ?? "world";
Can someone suggest a better way to write this check. Somehow the
number 11 is not looking good in the code.
Well you are accessing the element with 11 index, if you have that index in your variable then you can use that in your check, otherwise 11 is fine in your check. Your check should be if(index < snippetElements.Length)
Something like:
int index = 11;
if(index < snippetElements.Length)
{
string b = snippetElements[index] == null ? "" : "world";
}
snippetElements[11] is the 12th element.
if (snippetElements.Length >= 12)
As long your are actually using the [10] and [11] indexes it doesn't look wrong to use the 12 in the if statement.
You can generalize the problem to an extension method like this:
public static class ArrayExtensions
{
public static bool TryIndex<T>(this T[] array, int index, out T result)
{
index = Math.Abs(index);
result = default(T);
bool success = false;
if (array != null && index < array.Length)
{
result = (T)array.GetValue(index);
success = true;
}
return success;
}
}
And convert your code to:
string[] snippetElements = magic_string.Split('^');
string a = null;
string b = null;
if (snippetElements.TryIndex(10, out a) && snippetElements.TryIndex(11, out b))
{
}
Or, more like your source code and using the TryIndex(...) extension method:
string[] snippetElements = magic_string.Split('^');
string a = null;
string b = null;
snippetElements.TryIndex(10, out a);
snippetElements.TryIndex(11, out b);
a = a ?? "hello"; // Null coalesence ?? operator is great!
b = b ?? "world";
It makes the array indexed access safer since your code won't never throw ArgumentOutOfRangeException.
Note that this extension method will work for any kind of array, regardless of its type! Either if its a value type (int, byte...) or a reference type (string, your own classes...).
The logic here is wrong.
If your Split method produces less than 12 elements your indexing on the array snippetElements could go only from zero to (Length - 1) of the array.
In that case there aren't elements at index 10 or 11. And, in any case, if the snippetElement.Lenght is equal or greater than 12, then the elements in the array can't be null. Or they contain a string or they will be empty strings.
You could just write
string a = snippetElements.Length >= 12 ? "hello" : string.Empty;
string b = snippetElements.Length >= 12 ? "world" : string.Empty;
It might be late now, but for any one else who's having the same problem, that's how I solved it. I usually use this logic inside a for loop.
int index = 10;
string a = (index < snippetElements?.Length) ? snippetElements[index] : string.Empty;
snippetElements?.Length checks if snippetElements is not empty then it calls its Length property. Accessing Length property of an empty array results in an exception.
snippetElements[index] (you could replace this with "hello" as in your example) is accessed only if the index is in the bound of an array. Otherwise, it assigns String.Empty to a.

Does .net stop checking the rest of an IF statement if you use an and/or ( || / && )?

say you have something like:
int num = 0
then you do
if(num > 5 || num < 4)
{
...
}
it checks both, but what if you do
if(num < 4 || num > 5)
{
...
}
does it only check the 1st statement?
same as:
if(num > 5 && num == 0)
{
...
}
it should stop after failing the 1st and... right?
This is called boolean short-circuit evaluation and (although [citation-needed]) yes, C# and VB.NET have it (thanks #Lasse for the correction).
In C#, || and && are the short-circuited versions of | and &, respectively
.
Yes, this feature is called short circuit evaluation. If the first argument to the AND operator (&&) is false, then the entire expression will be false. Similarly with OR (||) if the first operand in true, the entire thing is true.
This feature is useful if you want to write the code similar to:
if(a != null && a.isValid())
... Code ...
This way you are not going to get an exception if a is null.
MSDN documentation http://msdn.microsoft.com/en-us/library/2a723cdk%28v=vs.71%29.aspx
If you do it right, yes. Take a look here: http://devpinoy.org/blogs/nocampo/archive/2007/09/28/short-circuit-evaluation-in-c-and-vb-net.aspx
EDIT: To clarify; C# yes, VB.NET if you use the right keywords.

Handling (2 raise to n) -1 conditions

I have one logical question. I have collection of employee objects
There are 3 filter criteria conditions which have handle
For e.g. Employee name, Office name, salary.
Now these filter criteria should match like (Employee name AND/OR Office name AND/OR salary)
So here I have to write (2 raise n) -1 if conditions to handle this situation.
Is there any other way we can do this.
For (Employee name AND/OR Office name) condition I m doing following
if (criteria.EmpName != "" && criteria.OfficeName != "")
{
if (emp.EmpName == criteria.EmpName && emp.OfficeName == criteria.OfficeName)
{
bIsMatch = true;
}
}
else
{
if (criteria.EmpName != "" && emp.EmpName == criteria.EmpName)
bIsMatch = true;
else if (criteria.OfficeName != "" && emp.OfficeName == criteria.OfficeName)
bIsMatch = true;
}
Now if have to handle saraly also i have write min 5 conditions.
Is thr other way to do it?
There are lots of ways to do it, but since you didn't specify one specific language and since I don't feel qualified to judge your coding style, here's one that keeps the general form of your code, while demonstrating some better logic:
bool bIsMatch = true;
if (criteria.EmpName != "" && criteria.EmpName != emp.EmpName) {
bIsMatch = false;
} else if (criteria.OfficeName != "" && criteria.OffIceName != emp.OfficeName) {
bIsMatch = false;
} /* Repeat for as many conditions as there are */
if (bIsMatch) {
/* None of the checks above failed */
}
You can pair up your filtering conditions and have a single statement that encodes all the parameters:
if( (criteria.EmpName.equals("") || criteria.EmpName.equals(emp.EmpName))
&& (criteria.OfficeName.equals("") || criteria.OfficeName.equals(emp.OfficeName))
&& (criteria.Salary.equals("") || criteria.Salary.equals(emp.Salary)))
In each of the AND-ed expressions checks first if the filter is empty, if it is that piece will result in true, if it's not, then the check is performed against the corresponding value in emp and is true only when that check is true.
Start out by assuming you have a match and Then apply each criterion one by one.
bIsMatch = true;
if (bIsMatch && criteria.EmpName != "") bIsMatch = emp.EmpName == criteria.EmpName;
if (bIsMatch && criteria.OfficeName != "") bIsMatch = emp.OfficeName == criteria.OfficeName;
// ...
Or, write a helper function that does the matching.
bool IsMatch(String criterion, String value)
{
return criterion == "" || criterion == value;
}
Then you can do everything in one big if statement:
if (IsMatch(criteria.EmpName, emp.EmpName) &&
IsMatch(criteria.OfficeName, emp.OfficeName) &&
...
)
You can check the criteria individually and maintain a count of matches. That way you need only n conditions:
int matches = 0;
if (criteria.EmpName != "" && emp.EmpName == criteria.EmpName)
matches++;
// similar code for other criteria
if (matches >= 2) { // as many matches as required
// succeeded
}
How about this? The idea scales well for more filters, except that the mapping itself is convention based (name - name).
var map = new Dictionary<string, string>
{
{ criteria.EmpName, emp.EmpName },
{ criteria.OfficeName, emp.OfficeName},
{ criteria.ThirdProp, emp.ThirdProp }
};
bIsMatch = dict.All(kvp => string.IsNullOrEmpty(kvp.Key) || kvp.Key == kvp.Value);
I would question the overall design though; there's something that doesn't seem right about it. How would you deal with the Salary field that you mention? Surely, that's not a string? What's the sentinel-value being used in that case?
Make sure you are clear enough about the business logic before writing the code. According to your code, I can see that you want to check if emp and criteria have the same EmployeeName and OfficeName, any of the properties is considered to be the same if it's string.Empty. The code will be quite clear after yourself is clear. Here we go:
public static bool EmptyOrEquals(this string one, string another)
{
return string.IsNullOrEmpty(another) || one.Equals(another);
}
bIsMatch = emp.EmpName.EmptyOrEquals(criteria.EmpName)
&& emp.OfficeName.EmptyOrEquals(criteria.OfficeName);
Test each question individually and use a bit set to encode the combinations of answers.
This results in cleaner code because you only test each criteria once, it's compact yet readable, and yet you can easily plug in code to handle each combination. And it's the fast too. O(n) to test all the criteria and O(1) to find the actual combination.
For a small, fixed number of criteria, you can push bits around manually. For many criteria, or for a solution that scales, use java.util.BitSet
Bit pushing example:
int bits = 0;
if (...criteria 1...) {
bits = 1;
}
if (...criteria 2...) {
bits |= 2;
}
if (...bits 3...) {
bits |= 4;
}
switch (bits) {
case 0: // no criteria matched
;
case 1: // criteria 1 matched
;
case 2: // criteria 2 matched
;
case 3: // criteria 1 AND 2 matched
;
case 4: // criteria 3 matched
;
case 5: // criteria 1 AND 3 matched
;
case 6: // criteria 2 AND 3 matched
;
case 7: // criteria 1 AND 2 AND 3 matched
;
}
You can generalize this solution using java.util.BitSet to manipulate bits for n criteria (useful when n > 64!). To facilitate quick look up, store the hash of each BitSet combination in a map that maps the hash code to a command class.

Categories

Resources