C#字符串大于或等于代码字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19132435/
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-10 14:11:04  来源:igfitidea点击:

C# String greater than or equal code string

c#stringstring-comparison

提问by Sneakybastardd

I'm trying to get my code working my comparing if a string is bigger or less than 10, but it doesn't work correctly. It writes 10 or more even if the value is less than 10.

如果字符串大于或小于 10,我正在尝试让我的代码进行比较,但它无法正常工作。即使值小于 10,它也会写入 10 或更多。

int result = string1.CompareTo("10");
if (result < 0)
{
     Console.WriteLine("less than 10");
}
else if (result >= 0)
{
     Console.WriteLine("10 or more");
} 

回答by Tim Schmelter

A string is not a number, so you're comparing lexicographically(from left to right). String.CompareTois used for ordering, but note that "10"is "lower" than "2"since the char 1is already lowerthan the char 2.

字符串不是数字,因此您要按字典顺序(从左到右)进行比较。String.CompareTo用于排序,但请注意它"10"“低于”"2"因为 char1已经低于char 2

I assume what you want want is to convert it to an int:

我假设您想要的是将其转换为int

int i1 = int.Parse(string1);
if (i1 < 10)
{
    Console.WriteLine("less than 10");
}
else if (i1 >= 10)
{
    Console.WriteLine("10 or more");
} 

Note that you should use int.TryParseif string1could have an invalid format. On that way you prevent an exception at int.Parse, e.g.:

请注意,您应该使用int.TryParseifstring1可能具有无效格式。通过这种方式,您可以防止在 处发生异常int.Parse,例如:

int i1;
if(!int.TryParse(string1, out i1))
{
    Console.WriteLine("Please provide a valid integer!");
}
else
{
    // code like above, i1 is the parsed int-value now
}


However, if you instead want to check if a string is longeror shorterthan 10 characters, you have to use it's Lengthproperty:

但是,如果您想检查字符串是长于还是于 10 个字符,则必须使用它的Length属性:

if (string1.Length < 10)
{
    Console.WriteLine("less than 10");
}
else if (string1.Length >= 10)
{
    Console.WriteLine("10 or more");
}