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
C# String greater than or equal code string
提问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.CompareTo
is used for ordering, but note that "10"
is "lower" than "2"
since the char 1
is 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.TryParse
if string1
could have an invalid format. On that way you prevent an exception at int.Parse
, e.g.:
请注意,您应该使用int.TryParse
ifstring1
可能具有无效格式。通过这种方式,您可以防止在 处发生异常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 Length
property:
但是,如果您想检查字符串是长于还是短于 10 个字符,则必须使用它的Length
属性:
if (string1.Length < 10)
{
Console.WriteLine("less than 10");
}
else if (string1.Length >= 10)
{
Console.WriteLine("10 or more");
}