I'd like to compare two string values, like this:
if (lblCapacity.Text <= lblSizeFile.Text)
How can I do it?
Using String. equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
We can simply compare them while ignoring the spaces using the built-in replaceAll() method of the String class: assertEquals(normalString. replaceAll("\\s+",""), stringWithSpaces. replaceAll("\\s+",""));
The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences. This method returns true if the strings are equal, and false if not.
I'm assuming that you are comparing strings in lexicographical order, in which case you can use the Static method String.Compare.
For example, you have two strings str1 and str2, and you want to see if str1 comes before str2 in an alphabet. Your code would look like this :
string str1 = "A string";
string str2 = "Some other string";
if(String.Compare(str1,str2) < 0)
{
// str1 is less than str2
Console.WriteLine("Yes");
}
else if(String.Compare(str1,str2) == 0)
{
// str1 equals str2
Console.WriteLine("Equals");
}
else
{
// str11 is greater than str2, and String.Compare returned a value greater than 0
Console.WriteLine("No");
}
This above code would return yes. There are many overloaded versions of String.Compare, including some where you can ignore case, or use format strings. Check out String.Compare.
int capacity;
int fileSize;
if (!int.TryParse(lblCapacity.Text, out capacity) //handle parsing problem;
if (!int.TryParse(lblSizeFile.Text, out fileSize) //handle parsing problem;
if (capacity <= fileSize) //... do something.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With