gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:05:37 25 4
gpt4 key购买 nike

如果字符串大于或小于 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用于排序,但请注意 "10""2"“低”,因为字符 1 已经 比 char 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如果 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
}

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

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

关于C#字符串大于等于代码字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19132435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com