Sne*_*rdd 5 c# string string-comparison
//你好,我试图让我的代码工作我的比较如果字符串更大或小于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");
}
Run Code Online (Sandbox Code Playgroud)
Tim*_*ter 21
字符串不是数字,因此您要按字典顺序(从左到右)进行比较.String.CompareTo用于排序,但要注意"10"是不是"低" "2",因为焦炭1已经是低比焦炭2.
我假设你想要的是将它转换为int:
int i1 = int.Parse(string1);
if (i1 < 10)
{
Console.WriteLine("less than 10");
}
else if (i1 >= 10)
{
Console.WriteLine("10 or more");
}
Run Code Online (Sandbox Code Playgroud)
请注意,您应该使用int.TryParseif string1可能具有无效格式.在这种情况下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
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您想要检查字符串是否长于或短于10个字符,则必须使用它的Length属性:
if (string1.Length < 10)
{
Console.WriteLine("less than 10");
}
else if (string1.Length >= 10)
{
Console.WriteLine("10 or more");
}
Run Code Online (Sandbox Code Playgroud)