问题描述
//你好,我试着让我的代码工作我比较一个字符串是否大于或小于10,但它不能正常工作。其写入10个或更多,甚至如果该值小于10
INT结果= string1.CompareTo(10)。
如果(结果℃,)
{
Console.WriteLine(小于10);
}
,否则如果(结果> = 0)
{
Console.WriteLine(10以上);
}
一个字符串是不是数字,所以你比较字典顺序(从左至右)。 如果字符串1
可以有一个无效的格式。在这种方式可以防止异常在 int.Parse
,例如:
INT I1; (!int.TryParse(字符串1,出I1))
如果
{
Console.WriteLine(请提供一个有效的整数!);
}
,否则
{
//像上面的代码中,I1为解析的INT-值现在
}
然而,如果你不是想检查一个字符串的长或缩短的超过10个字符,你必须使用它的属性:
如果(string1.Length小于10)
{
Console.WriteLine(小于10);
}
,否则如果(string1.Length> = 10)
{
Console.WriteLine(10以上);
}
// Hello, Im 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.
int result = string1.CompareTo("10");
if (result < 0)
{
Console.WriteLine("less than 10");
}
else if (result >= 0)
{
Console.WriteLine("10 or more");
}
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 lower than the char 2
.
I assume what you want want is to convert it to an 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 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 longer or shorter than 10 characters, you have to use it's Length
property:
if (string1.Length < 10)
{
Console.WriteLine("less than 10");
}
else if (string1.Length >= 10)
{
Console.WriteLine("10 or more");
}
这篇关于C#字符串大于或等于码串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!