C#字符串大于或等于码串 [英] C# String greater than or equal code string

查看:423
本文介绍了C#字符串大于或等于码串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//你好,我试着让我的代码工作我比较一个字符串是否大于或小于10,但它不能正常工作。其写入10个或更多,甚至如果该值小于10



  INT结果= string1.CompareTo(10)。 
如果(结果℃,)
{
Console.WriteLine(小于10);
}
,否则如果(结果> = 0)
{
Console.WriteLine(10以上);
}


解决方案

一个字符串是不是数字,所以你比较字典顺序(从左至右)。 String.CompareTo 用于排序,但请注意,10是低于2由于字符 1 已经的的比字符 2



我想,你希望要的是将其转换为一个 INT

  INT I1 = int.Parse(字符串1); 
如果(I1小于10)
{
Console.WriteLine(小于10);
}
,否则如果(I1> = 10)
{
Console.WriteLine(10以上);
}

请注意,你应该使用的 int.TryParse 如果字符串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#字符串大于或等于码串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆