检查是否可以在不使用int.TryParse的情况下将字符串转换为整数? [英] Check if a string can be converted to an integer without using int.TryParse?

查看:68
本文介绍了检查是否可以在不使用int.TryParse的情况下将字符串转换为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,能否让我知道某种方法来检查是否可以使用int.TryParse将字符串转换为整数而无需使用int.TryParse或通过字符串的所有字符进行循环.我想要一种使用可用类(内置.NET库)进行检查的方法.
非常感谢!

Hi, could you please let me know some way to check if a string can be converted to an integer WITHOUT using int.TryParse or a loop through all characters of the string. I want a way to check using an available class (built-in .NET library).
Thank you so much!

推荐答案

在我们得到答案之前,很难说一个问题是否有意义,不是很合逻辑吗?

让我们看看:
It''s hard to say if a Question makes any sense or not before we have an Answer, isn''t that logical?

Let''s see:
static bool TryParse(string input, out int output) {
    try {
        output = int.Parse(input);
        return true;
    } catch {
        output = default(int);
        return false;
    }
}



我们确实需要捕获所有异常,因为input字符串可以是任何东西.

因此,任何字符串检查都是毫无意义的.
这是怎么回事:



We really need to catch all exception, as an input string can be anything.

For that reason, any string checks are pointless.
What''s wrong with this:

//incorrect!
static bool CheckInteger(string value) {
   var regex = new System.Text.RegularExpressions.Regex("^[0-9]+


" ); 返回 regex.IsMatch(" ); }
"); return regex.IsMatch("1"); }



它不仅会进行冗余检查(无论如何下一步都必须为ParseTryParse),而且还会出错.传递"9999999999"的值-它会返回true,但由于溢出而不会解析.

第一种方法bool TryParse(string, our int)有什么问题?没错,这是正确的,只有……如果我们已经有了int.TryParse,为什么还要编写它?

不,这没有任何意义.

-SA



Not only it does redundant check (next step must be Parse or TryParse anyway), but it also wrong. Pass the value of "9999999999" — it will return true but won''t parse due to overflow.

What''s wrong with the first method bool TryParse(string, our int)? Nothing wrong, it''s correct, only… why writing it if we already have int.TryParse?

No, it does not make any sense.

—SA


string myString = "12345m?";
string numbers = "0123456789";
var count = (from ch in myString 
             where !numbers.Contains(ch)
             select ch).Count();
bool isNumber = (count == 0);



当然,以上代码使用了内置的框架函数,因此您可能同样感到困惑(但这并没有真正让我感到困扰,因为您是在课堂上没有注意的人,而不是我).



Of course, the above uses a built-in framework function, so you might be equally screwed (but that doesn''t really bother me since you''re the one that wasn''t paying attention in class, not me).


这篇关于检查是否可以在不使用int.TryParse的情况下将字符串转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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