我试图让我的代码能够比较字符串是否大于或小于 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");
}
字符串不是数字,因此您要按字典顺序进行比较(从左到右)。String.CompareTo http://msdn.microsoft.com/en-us/library/35f0x18w.aspx用于订购,但请注意"10"
“低于”"2"
自从炭1
已经lower比炭2
.
我假设你想要的是将其转换为int
:
int i1 = int.Parse(string1);
if (i1 < 10)
{
Console.WriteLine("less than 10");
}
else if (i1 >= 10)
{
Console.WriteLine("10 or more");
}
请注意,您应该使用int.TryParse http://msdn.microsoft.com/en-us/library/f02979c7.aspx if string1
可能有无效的格式。这样你就可以防止异常int.Parse
, e.g.:
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
}
但是,如果您想检查字符串是否是longer or shorter超过10个字符,你必须使用它Length http://msdn.microsoft.com/en-us/library/system.string.length.aspx财产:
if (string1.Length < 10)
{
Console.WriteLine("less than 10");
}
else if (string1.Length >= 10)
{
Console.WriteLine("10 or more");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)