检查字符串是否可以解析为Long而不使用try-catch? [英] Check whether a string is parsable into Long without try-catch?

查看:107
本文介绍了检查字符串是否可以解析为Long而不使用try-catch?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果字符串无法解析为long,则Long.parseLong(string)会引发错误。
有没有办法比使用 try-catch 更快地验证字符串?
谢谢

Long.parseLong("string") throws an error if string is not parsable into long. Is there a way to validate the string faster than using try-catch? Thanks

推荐答案

你可以创建相当复杂的正则表达式,但这不值得。在这里使用例外是绝对正常的。

You can create rather complex regular expression but it isn't worth that. Using exceptions here is absolutely normal.

这是自然的例外情况:你假设字符串中有一个整数,但确实还有其他东西。应该抛出并正确处理异常。

It's natural exceptional situation: you assume that there is an integer in the string but indeed there is something else. Exception should be thrown and handled properly.

如果你查看 parseLong 代码,你会看到有许多不同的验证和操作。如果你想在解析它之前做所有这些事情会降低性能(如果我们谈论解析数百万个数字,因为否则无关紧要)。所以,你唯一可以做的事情如果你真的需要通过避免异常来提高性能是:将 parseLong 实现复制到你自己的函数并返回NaN而不是在所有通讯案件中抛出异常。

If you look inside parseLong code, you'll see that there are many different verifications and operations. If you want to do all that stuff before parsing it'll decrease the performance (if we are talking about parsing millions of numbers because otherwise it doesn't matter). So, the only thing you can do if you really need to improve performance by avoiding exceptions is: copy parseLong implementation to your own function and return NaN instead of throwing exceptions in all correspondent cases.

这篇关于检查字符串是否可以解析为Long而不使用try-catch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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