我通常使用以下习语来检查String是否可以转换为整数。
public boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
是我的错觉,还是你觉得这有点粗俗?还有什么更好的办法吗?
看看我的回答(带有基准,基于CodingWithSpike之前的回答),看看为什么我改变了立场,接受了Jonas Klemming对这个问题的回答。我认为大多数人都会使用这个原始代码,因为它实现起来更快,也更易于维护,但是当提供非整数数据时,它就慢了几个数量级。
做了一个快速的基准测试。异常实际上并没有那么昂贵,除非您开始弹出多个方法,JVM必须做大量工作才能使执行堆栈就位。如果保持相同的方法,他们就不会表现不好。
public void RunTests()
{
String str = "1234567890";
long startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByException(str);
long endTime = System.currentTimeMillis();
System.out.print("ByException: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByRegex(str);
endTime = System.currentTimeMillis();
System.out.print("ByRegex: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByJonas(str);
endTime = System.currentTimeMillis();
System.out.print("ByJonas: ");
System.out.println(endTime - startTime);
}
private boolean IsInt_ByException(String str)
{
try
{
Integer.parseInt(str);
return true;
}
catch(NumberFormatException nfe)
{
return false;
}
}
private boolean IsInt_ByRegex(String str)
{
return str.matches("^-?\\d+$");
}
public boolean IsInt_ByJonas(String str)
{
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = str.charAt(i);
if (c <= '/' || c >= ':') {
return false;
}
}
return true;
}
输出:
ByException: 31
ByRegex: 453(注意:每次都重新编译模式)
ByJonas: 16
我也同意Jonas K的解决方案是最稳健的。看起来他赢了:)
我从rally25rs answer复制了代码,并添加了一些非整数数据的测试。结果不可否认地支持Jonas Klemming发布的方法。当你有整数数据时,我最初发布的Exception方法的结果非常好,但当你没有整数数据时,它们是最糟糕的,而RegEx解决方案(我敢打赌很多人使用)的结果一直很糟糕。请参阅Felipe的编译正则表达式示例,该示例要快得多。
public void runTests()
{
String big_int = "1234567890";
String non_int = "1234XY7890";
long startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByException(big_int);
long endTime = System.currentTimeMillis();
System.out.print("ByException - integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByException(non_int);
endTime = System.currentTimeMillis();
System.out.print("ByException - non-integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByRegex(big_int);
endTime = System.currentTimeMillis();
System.out.print("\nByRegex - integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByRegex(non_int);
endTime = System.currentTimeMillis();
System.out.print("ByRegex - non-integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByJonas(big_int);
endTime = System.currentTimeMillis();
System.out.print("\nByJonas - integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByJonas(non_int);
endTime = System.currentTimeMillis();
System.out.print("ByJonas - non-integer data: ");
System.out.println(endTime - startTime);
}
private boolean IsInt_ByException(String str)
{
try
{
Integer.parseInt(str);
return true;
}
catch(NumberFormatException nfe)
{
return false;
}
}
private boolean IsInt_ByRegex(String str)
{
return str.matches("^-?\\d+$");
}
public boolean IsInt_ByJonas(String str)
{
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = str.charAt(i);
if (c <= '/' || c >= ':') {
return false;
}
}
return true;
}
结果:
ByException - integer data: 47
ByException - non-integer data: 547
ByRegex - integer data: 390
ByRegex - non-integer data: 313
ByJonas - integer data: 0
ByJonas - non-integer data: 16
因为有可能人们仍然访问这里,并且在基准测试之后会对Regex产生偏见……因此,我将给出基准测试的更新版本,以及Regex的编译版本。与之前的基准测试相反,这个测试显示Regex解决方案实际上始终具有良好的性能。
摘自《蜥蜴比尔》,经编译后更新:
private final Pattern pattern = Pattern.compile("^-?\\d+$");
public void runTests() {
String big_int = "1234567890";
String non_int = "1234XY7890";
long startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByException(big_int);
long endTime = System.currentTimeMillis();
System.out.print("ByException - integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByException(non_int);
endTime = System.currentTimeMillis();
System.out.print("ByException - non-integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByRegex(big_int);
endTime = System.currentTimeMillis();
System.out.print("\nByRegex - integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByRegex(non_int);
endTime = System.currentTimeMillis();
System.out.print("ByRegex - non-integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
IsInt_ByCompiledRegex(big_int);
endTime = System.currentTimeMillis();
System.out.print("\nByCompiledRegex - integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
IsInt_ByCompiledRegex(non_int);
endTime = System.currentTimeMillis();
System.out.print("ByCompiledRegex - non-integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByJonas(big_int);
endTime = System.currentTimeMillis();
System.out.print("\nByJonas - integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByJonas(non_int);
endTime = System.currentTimeMillis();
System.out.print("ByJonas - non-integer data: ");
System.out.println(endTime - startTime);
}
private boolean IsInt_ByException(String str)
{
try
{
Integer.parseInt(str);
return true;
}
catch(NumberFormatException nfe)
{
return false;
}
}
private boolean IsInt_ByRegex(String str)
{
return str.matches("^-?\\d+$");
}
private boolean IsInt_ByCompiledRegex(String str) {
return pattern.matcher(str).find();
}
public boolean IsInt_ByJonas(String str)
{
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = str.charAt(i);
if (c <= '/' || c >= ':') {
return false;
}
}
return true;
}
结果:
ByException - integer data: 45
ByException - non-integer data: 465
ByRegex - integer data: 272
ByRegex - non-integer data: 131
ByCompiledRegex - integer data: 45
ByCompiledRegex - non-integer data: 26
ByJonas - integer data: 8
ByJonas - non-integer data: 2
我相信遇到异常的风险为零,因为正如你在下面看到的,你总是安全地将int解析为String,而不是相反。
So:
检查字符串中的每个字符槽是否至少匹配
人物之一{“0”、“1”、“2”、“3”、“4”、“5”、“6”、“7”、“8”,“9”}。
如果(aString。substring (j, + 1) .equals (String.valueOf(我)))
你把你在上面的槽中遇到的所有时间加起来
字符。
数字+ +;
最后检查遇到整数的次数是否为
Characters等于给定字符串的长度。
if(digits == aString.length())
在实践中我们有:
String aString = "1234224245";
int digits = 0;//count how many digits you encountered
for(int j=0;j<aString.length();j++){
for(int i=0;i<=9;i++){
if(aString.substring(j, j+1).equals(String.valueOf(i)))
digits++;
}
}
if(digits == aString.length()){
System.out.println("It's an integer!!");
}
else{
System.out.println("It's not an integer!!");
}
String anotherString = "1234f22a4245";
int anotherDigits = 0;//count how many digits you encountered
for(int j=0;j<anotherString.length();j++){
for(int i=0;i<=9;i++){
if(anotherString.substring(j, j+1).equals(String.valueOf(i)))
anotherDigits++;
}
}
if(anotherDigits == anotherString.length()){
System.out.println("It's an integer!!");
}
else{
System.out.println("It's not an integer!!");
}
结果是:
是个整数!!
不是整数!!
类似地,您可以验证String是float还是double,但在这些情况下,您只需要遇到一个。(dot)在字符串中当然检查digits是否== (aString.length()-1)
同样,这里遇到解析异常的风险为零,但是如果您计划解析一个已知包含数字的字符串(比如int数据类型),则必须首先检查它是否适合该数据类型。否则你必须施放它。
我希望我能帮上忙
这是一个Java 8版本的Jonas Klemming回答:
public static boolean isInteger(String str) {
return str != null && str.length() > 0 &&
IntStream.range(0, str.length()).allMatch(i -> i == 0 && (str.charAt(i) == '-' || str.charAt(i) == '+')
|| Character.isDigit(str.charAt(i)));
}
测试代码:
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
Arrays.asList("1231231", "-1232312312", "+12313123131", "qwqe123123211", "2", "0000000001111", "", "123-", "++123",
"123-23", null, "+-123").forEach(s -> {
System.out.printf("%15s %s%n", s, isInteger(s));
});
}
测试代码的结果:
1231231 true
-1232312312 true
+12313123131 true
qwqe123123211 false
2 true
0000000001111 true
false
123- false
++123 false
123-23 false
null false
+-123 false
如果你想检查字符串是否代表一个适合int类型的整数,我对jonas的答案做了一点修改,以便字符串表示大于integer的整数。MAX_VALUE或小于Integer。MIN_VALUE,现在将返回false。例如:"3147483647"将返回false,因为3147483647大于2147483647,同样,"-2147483649"也将返回false,因为-2147483649小于-2147483648。
public static boolean isInt(String s) {
if(s == null) {
return false;
}
s = s.trim(); //Don't get tricked by whitespaces.
int len = s.length();
if(len == 0) {
return false;
}
//The bottom limit of an int is -2147483648 which is 11 chars long.
//[note that the upper limit (2147483647) is only 10 chars long]
//Thus any string with more than 11 chars, even if represents a valid integer,
//it won't fit in an int.
if(len > 11) {
return false;
}
char c = s.charAt(0);
int i = 0;
//I don't mind the plus sign, so "+13" will return true.
if(c == '-' || c == '+') {
//A single "+" or "-" is not a valid integer.
if(len == 1) {
return false;
}
i = 1;
}
//Check if all chars are digits
for(; i < len; i++) {
c = s.charAt(i);
if(c < '0' || c > '9') {
return false;
}
}
//If we reached this point then we know for sure that the string has at
//most 11 chars and that they're all digits (the first one might be a '+'
// or '-' thought).
//Now we just need to check, for 10 and 11 chars long strings, if the numbers
//represented by the them don't surpass the limits.
c = s.charAt(0);
char l;
String limit;
if(len == 10 && c != '-' && c != '+') {
limit = "2147483647";
//Now we are going to compare each char of the string with the char in
//the limit string that has the same index, so if the string is "ABC" and
//the limit string is "DEF" then we are gonna compare A to D, B to E and so on.
//c is the current string's char and l is the corresponding limit's char
//Note that the loop only continues if c == l. Now imagine that our string
//is "2150000000", 2 == 2 (next), 1 == 1 (next), 5 > 4 as you can see,
//because 5 > 4 we can guarantee that the string will represent a bigger integer.
//Similarly, if our string was "2139999999", when we find out that 3 < 4,
//we can also guarantee that the integer represented will fit in an int.
for(i = 0; i < len; i++) {
c = s.charAt(i);
l = limit.charAt(i);
if(c > l) {
return false;
}
if(c < l) {
return true;
}
}
}
c = s.charAt(0);
if(len == 11) {
//If the first char is neither '+' nor '-' then 11 digits represent a
//bigger integer than 2147483647 (10 digits).
if(c != '+' && c != '-') {
return false;
}
limit = (c == '-') ? "-2147483648" : "+2147483647";
//Here we're applying the same logic that we applied in the previous case
//ignoring the first char.
for(i = 1; i < len; i++) {
c = s.charAt(i);
l = limit.charAt(i);
if(c > l) {
return false;
}
if(c < l) {
return true;
}
}
}
//The string passed all tests, so it must represent a number that fits
//in an int...
return true;
}
当解释比表现更重要时
我注意到许多讨论都围绕着某些解决方案的效率,但没有一个讨论为什么字符串不是整数。而且,每个人似乎都认为数字“2.00”不等于“2”。从数学和人类的角度来说,它们是平等的(尽管计算机科学说它们不是,而且有充分的理由)。这就是为什么“Integer.”上面的parseInt”解决方案是弱的(取决于您的需求)。
无论如何,为了使软件更智能、更人性化,我们需要创造出能够像我们一样思考并能解释失败原因的软件。在这种情况下:
public static boolean isIntegerFromDecimalString(String possibleInteger) {
possibleInteger = possibleInteger.trim();
try {
// Integer parsing works great for "regular" integers like 42 or 13.
int num = Integer.parseInt(possibleInteger);
System.out.println("The possibleInteger="+possibleInteger+" is a pure integer.");
return true;
} catch (NumberFormatException e) {
if (possibleInteger.equals(".")) {
System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it is only a decimal point.");
return false;
} else if (possibleInteger.startsWith(".") && possibleInteger.matches("\\.[0-9]*")) {
if (possibleInteger.matches("\\.[0]*")) {
System.out.println("The possibleInteger=" + possibleInteger + " is an integer because it starts with a decimal point and afterwards is all zeros.");
return true;
} else {
System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it starts with a decimal point and afterwards is not all zeros.");
return false;
}
} else if (possibleInteger.endsWith(".") && possibleInteger.matches("[0-9]*\\.")) {
System.out.println("The possibleInteger="+possibleInteger+" is an impure integer (ends with decimal point).");
return true;
} else if (possibleInteger.contains(".")) {
String[] partsOfPossibleInteger = possibleInteger.split("\\.");
if (partsOfPossibleInteger.length == 2) {
//System.out.println("The possibleInteger=" + possibleInteger + " is split into '" + partsOfPossibleInteger[0] + "' and '" + partsOfPossibleInteger[1] + "'.");
if (partsOfPossibleInteger[0].matches("[0-9]*")) {
if (partsOfPossibleInteger[1].matches("[0]*")) {
System.out.println("The possibleInteger="+possibleInteger+" is an impure integer (ends with all zeros after the decimal point).");
return true;
} else if (partsOfPossibleInteger[1].matches("[0-9]*")) {
System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it the numbers after the decimal point (" +
partsOfPossibleInteger[1] + ") are not all zeros.");
return false;
} else {
System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it the 'numbers' after the decimal point (" +
partsOfPossibleInteger[1] + ") are not all numeric digits.");
return false;
}
} else {
System.out.println("The possibleInteger=" + possibleInteger + " is NOT an integer because it the 'number' before the decimal point (" +
partsOfPossibleInteger[0] + ") is not a number.");
return false;
}
} else {
System.out.println("The possibleInteger="+possibleInteger+" is NOT an integer because it has a strange number of decimal-period separated parts (" +
partsOfPossibleInteger.length + ").");
return false;
}
} // else
System.out.println("The possibleInteger='"+possibleInteger+"' is NOT an integer, even though it has no decimal point.");
return false;
}
}
测试代码:
String[] testData = {"0", "0.", "0.0", ".000", "2", "2.", "2.0", "2.0000", "3.14159", ".0001", ".", "$4.0", "3E24", "6.0221409e+23"};
int i = 0;
for (String possibleInteger : testData ) {
System.out.println("");
System.out.println(i + ". possibleInteger='" + possibleInteger +"' isIntegerFromDecimalString=" + isIntegerFromDecimalString(possibleInteger));
i++;
}
我不喜欢方法与regex,因为regex不能检查范围(整数。MIN_VALUE Integer.MAX_VALUE)。
如果你希望在大多数情况下使用int值,而不是int值是不常见的,那么我建议使用Integer。valueOf或Integer。parseInt与NumberFormatException捕获。这种方法的优点-你的代码有很好的可读性:
public static boolean isInt(String s) {
try {
Integer.parseInt(s);
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
如果你需要检查String是否为整数,并且关心性能,那么最好的方法是使用java jdk实现的integer。parseInt,但很少修改(用return false替换throw):
该功能性能良好,保证正确的结果:
public static boolean isInt(String s) {
int radix = 10;
if (s == null) {
return false;
}
if (radix < Character.MIN_RADIX) {
return false;
}
if (radix > Character.MAX_RADIX) {
return false;
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
return false;
if (len == 1) // Cannot have lone "+" or "-"
return false;
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++), radix);
if (digit < 0) {
return false;
}
if (result < multmin) {
return false;
}
result *= radix;
if (result < limit + digit) {
return false;
}
result -= digit;
}
} else {
return false;
}
return true;
}
你可以:
检查字符串是否为数字
检查它是否太长而不能被解析为long
检查结果的长值是否小到可以用整型表示
(假设您出于某种原因必须自己实现此功能:您可能应该首先查看com.google.common.primitives.Ints.tryParse(String),并查看它是否足够适合您的目的(正如另一个答案所建议的那样)。)
// Credit to Rastislav Komara’s answer: https://stackoverflow.com/a/237895/1725151
private static final Pattern nonZero = Pattern.compile("^-?[1-9]\\d*$");
// See if `str` can be parsed as an `int` (does not trim)
// Strings like `0023` are rejected (leading zeros).
public static boolean parsableAsInt(@Nonnull String str) {
if (str.isEmpty()) {
return false;
}
if (str.equals("0")) {
return true;
}
if (canParseAsLong(str)) {
long value = Long.valueOf(str);
if (value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE) {
return true;
}
}
return false;
}
private static boolean canParseAsLong(String str) {
final int intMaxLength = 11;
return str.length() <= intMaxLength && nonZero.matcher(str).matches();
}
这个方法也可以转换为返回Optional<Integer>,这样你就不必在客户端代码中解析两次字符串了(一次是为了检查是否可行,第二次是为了“真正地”执行它)。例如:
if (canParseAsLong(str)) {
long value = Long.valueOf(str);
if (value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE) {
return Optional.of((int) value);
}
}
I recently (today) needed to figure out a quick way to do this and of course I was going to use the exception approach for ease when the monkey on the shoulder (conscience) woke up so it took me down this old familiar rabbit hole; no exceptions are not that much more expensive in fact sometimes exceptions are faster (old AIX multiprocessor systems) but regardless it’s to elegant so I did something that the younger me never did and to my amazement nobody here did either (apologize if someone did and I missed it I honestly did not find) : so what did I think we all missed; taking a look at how the JRE implemented it, yes they threw an exception but we can always skip that part.
10年前年轻的我可能会觉得这有失他的身份,但话又说回来,他是一个大嘴巴的炫耀者,性情不好,有一种神的情结,所以就是这样。
我把这些放在这里,是为了方便将来来这里的人。以下是我的发现:
public static int parseInt(String s, int radix) throws NumberFormatException
{
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}