C# 比较两个字符串值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10280994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:09:23  来源:igfitidea点击:

compare two string value

c#stringcompare

提问by Atoxis

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

我想比较两个字符串值??,像这样:

if (lblCapacity.Text <= lblSizeFile.Text)

How can I do it?

我该怎么做?

回答by Mr.Pe

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

使用Int32.ParseInt32.TryParse或其他等效物。然后,您可以对这些值进行数字比较。

回答by Botz3000

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

看起来标签包含数字。那么你可以尝试Int32.Parse

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

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

当然,您可能想要添加一些错误检查(查看Int32.TryParse并可能将解析的 int 值存储在某些变量中,但这是基本概念。

回答by Marshal

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
    }
}

回答by Matt

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.

回答by Yeshvanthni

Compare is what you need.

比较是你需要的。

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

回答by Aaron Deming

I'm assuming that you are comparing strings in lexicographical order, in which case you can use the Static method String.Compare.

我假设您正在按字典顺序比较字符串,在这种情况下,您可以使用静态方法 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 :

例如,您有两个字符串 str1 和 str2,您想查看在字母表中 str1 是否在 str2 之前。您的代码如下所示:

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.

上面的代码将返回 yes。String.Compare 有许多重载版本,包括一些可以忽略大小写或使用格式字符串的版本。查看String.Compare