compare two string value [closed]

落花浮王杯 提交于 2019-12-01 01:38:36

问题


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

if (lblCapacity.Text <= lblSizeFile.Text)

How can I do it?


回答1:


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.




回答2:


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.



回答3:


If you have integers in textbox then,

int capacity;
int fileSize;

if(Int32.TryParse(lblCapacity.Text,out capacity) && 
   Int32.TryParse(lblSizeFile.Text,out fileSize))
{
    if(capacity<=fileSize)
    {
        //do something
    }
}



回答4:


Looks like the labels contain numbers. Then you could try Int32.Parse:

if (int.Parse(lblCapacity.Text) <= int.Parse(lblSizeFile.Text))

Of course you might want to add some error checking (look at Int32.TryParse and maybe store the parsed int values in some variables, but this is the basic concept.




回答5:


Compare is what you need.

int c = string.Compare(a , b);



回答6:


Use Int32.Parse, Int32.TryParse or other equivalent. You can then numerically compare these values.



来源:https://stackoverflow.com/questions/10280994/compare-two-string-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!