Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare two string value [closed]

Tags:

string

c#

compare

I'd like to compare two string values​​, like this:

if (lblCapacity.Text <= lblSizeFile.Text)

How can I do it?

like image 827
Atoxis Avatar asked Apr 23 '12 12:04

Atoxis


People also ask

How do you compare two string values?

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.

Can you use == to compare strings?

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.

How do you compare two strings without spaces?

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+",""));

Which method is used to compare two strings ignoring the case?

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.


2 Answers

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.

like image 145
Aaron Deming Avatar answered Oct 07 '22 00:10

Aaron Deming


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.
like image 34
Matt Avatar answered Oct 07 '22 01:10

Matt