java 以安全的方式将字符串转换为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16908029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:21:09  来源:igfitidea点击:

Converting String to Integers the safe way

javatype-conversion

提问by felix fritz

I have a little method that amongst other things also converts a string into an integer. Since the string is a parameter of the method I want to make sure that that string is convertable. So I was just wondering what would be the safest and / or fastest way.

我有一个小方法,除其他外,还可以将字符串转换为整数。由于字符串是方法的参数,我想确保该字符串是可转换的。所以我只是想知道什么是最安全和/或最快的方法。



Version A: Just leave it as it is and take the risks (which I'm trying to avoid)

版本 A:保持原样并承担风险(我试图避免)

public static int stringToInt(String param) {
        return Integer.valueOf(param);
}

(in terms of speed, what kind of difference would it make to version B and C?)

(速度方面,B版和C版有什么区别?)



Version B: Catch the exception

版本 B:捕捉异常

public static int stringToInt(String param) {
        try {
                return Integer.valueOf(param);
        } catch(NumberFormatException e) {
                return -1;
        }
}


Version C: Check each letter of the string to see, if it's a digit number or not

版本 C:检查字符串的每个字母以查看它是否是数字

public static int stringToInt(String param) {
        for(char c : param.toCharArray()) {
                if(!Character.isDigit(c))
                        return -1;
        }
        return Integer.valueOf(param);
}


Note that the parameter has to be a positive number and the -1 is supposed to be the "error value" in my little program, in other words, all three versions of methods would work perfectally fine in my program.

请注意,参数必须是正数,而 -1 应该是我的小程序中的“错误值”,换句话说,所有三个版本的方法在我的程序中都可以正常工作。

I'm very open to any other suggestion you can give me, so feel free to create your own version, if you think yours is better.

我很乐意接受您给我的任何其他建议,所以如果您认为自己的版本更好,请随时创建自己的版本。

Thank you very much for your support in advance.

非常感谢您的支持。

采纳答案by dasblinkenlight

First, note that version Cis not bulletproof: it would reject negative numbers, and would not catch numbers that are too large.

首先,请注意 versionC不是防弹的:它会拒绝负数,并且不会捕获太大的数字。

Version Bis OK, yet it makes the caller change the coding style: rather than catching an error and processing it together with other errors, the caller would need to check for -1all the time. This may be suboptimal in situations where you read multiple integers, but the error processing does not depend on which particular one has failed. In addition, new coders using your API may forget to check for -1, and use the error code inadvertently.

版本没问题B,但它使调用者改变了编码风格:调用者需要一直检查,而不是捕捉错误并将其与其他错误一起处理-1。在您读取多个整数的情况下,这可能不是最理想的,但错误处理不取决于哪个特定的失败。此外,使用您的 API 的新编码人员可能会忘记检查-1,并在不经意间使用错误代码。

That's why I would stay with the first option: the code using version Awould look instantly familiar to anyone who knows Java API, without the need to learn what happens inside your function.

这就是为什么我会保留第一个选项:使用 version 的代码A对于了解 Java API 的任何人来说都会立即看起来很熟悉,而无需了解您的函数内部发生了什么。

回答by user828878

Guava offers a utility method for this which returns null in case your String can't be parsed.

Guava 为此提供了一个实用方法,如果您的 String 无法解析,它会返回 null。

https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Ints.html#tryParse(java.lang.String)

https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Ints.html#tryParse(java.lang.String)

Integer result = Ints.tryParse("1");  //returns 1
Integer result = Ints.tryParse("-1"); //returns -1
Integer result = Ints.tryParse("a");  //returns null

回答by Juned Ahsan

I believe a modified B to throw an exception rather than returning -1 will be the best choice. It is good to throw the exception up to the level, where it can be processed to send the proper response to the user. Returning a value like -1 will make your code error prone. Assume that a different programmer is consuming your method and he/she just have the signature of your method. So it is not clear from the signature what he/she should code to handle an exception or error scenario. But if you throw the exception and add it to your method declaration then it will enable the other programmer to consume your method properly alongwith the required exception handling. For me this looks the best:

我相信修改后的 B 抛出异常而不是返回 -1 将是最好的选择。最好将异常抛出到可以处理它以向用户发送正确响应的级别。返回一个像 -1 这样的值会使你的代码容易出错。假设另一个程序员正在使用您的方法,而他/她只有您的方法的签名。因此,从签名中不清楚他/她应该编码什么来处理异常或错误情况。但是,如果您抛出异常并将其添加到您的方法声明中,那么它将使其他程序员能够正确使用您的方法以及所需的异常处理。对我来说,这看起来最好:

public static int stringToInt(String param) throws NumberFormatException {
        try {
                return Integer.valueOf(param);
        } catch(NumberFormatException e) {
               // return -1;
               throw e;
        }
}

回答by Clifford Fernandes

Java 8 without any API:

没有任何 API 的 Java 8:

 Optional.ofNullable(strNum)
         .map(Integer::valueOf).orElse(null);

回答by N Djel Okoye

public int stringToInt(String param) throws NumberFormatException {

    Optional.ofNullable(param.replaceAll("\s+", ""))
         .map(Integer::valueOf).orElse(null);

/*
                      or

    Optional.ofNullable(param.replaceAll(" ", ""))
         .map(Integer::valueOf).orElse(null);

*/

}

use the replaceAll to replace white spaces the plus is cpu friendly even though seems not needed.

使用 replaceAll 替换空格加号是 cpu 友好的,即使似乎不需要。