문자열이 Java에서 정수를 나타내는지 확인하는 가장 좋은 방법은 무엇입니까?
String을 정수로 변환할 수 있는지 확인하기 위해 보통 다음과 같은 관용어를 사용합니다.
public boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
나만 그런가, 아니면 이게 좀 해킹처럼 보이는가?어떻게 하면 좋을까요?
이 문제에 대한 나의 입장을 뒤집고 Jonas Klemming의 답변을 받아들인 이유를 보려면 벤치마크와 함께 내 답변을 참조하십시오.이 오리지널 코드는 구현이 빠르고 유지보수가 용이하기 때문에 대부분의 사람들이 사용할 것이라고 생각합니다만, 정수 이외의 데이터가 제공되면 훨씬 느려집니다.
경우 이 는 사용 중인 오버플로우보다 약됩니다.Integer.parseInt()
.
public static boolean isInteger(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 < '0' || c > '9') {
return false;
}
}
return true;
}
있지만,은 오직, 잡으면 안 요.NumberFormatException
.
간단한 벤치마크를 했다.여러 가지 방법을 사용하기 시작하고 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;
}
출력:
예외 기준: 31
ByRegex: 453 (메모: 매번 패턴 재컴파일)
작성자: 16
나는 Jonas K의 솔루션이 가장 강력하다는 것에 동의한다.그가 이길 것 같아 :)
org.apache.commons.lang.StringUtils.isNumeric
Java의 표준 lib는 실제로 그러한 유틸리티 기능을 놓치고 있지만
Apache Commons는 모든 자바 프로그래머에게 필수라고 생각합니다.
아직 Java5로 포팅되지 않아 아쉽다.
사람들이 여전히 이곳을 방문할 가능성이 있고 벤치마크가 끝난 후에도 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
이는 부분적으로 "정수로 변환할 수 있다"는 의미에 따라 달라집니다.
"Java에서 int로 변환할 수 있다"는 의미라면 Jonas의 답변은 시작은 좋지만 작업이 완전히 끝나지는 않습니다.예를 들어 9999999999999999999999999999999를 통과합니다.이 메서드의 마지막에 고객님의 질문에서 일반적인 시도/캐치 콜을 추가합니다.
문자별 체크는 "전혀 정수가 아니다" 케이스를 효율적으로 거부하여 "정수이지만 Java는 처리할 수 없다" 케이스를 느린 예외 경로로 포착합니다.이것도 수작업으로 할 수 있지만 훨씬 더 복잡할 거예요.
regexp에 대한 코멘트는 1개뿐입니다.여기에 제시된 예제는 모두 틀렸습니다!regexp를 사용하는 경우 패턴을 컴파일하는 데 많은 시간이 걸린다는 것을 잊지 마십시오.이것은, 다음과 같습니다.
str.matches("^-?\\d+$")
또, 다음과 같은 것도 있습니다.
Pattern.matches("-?\\d+", input);
는 모든 메서드콜의 패턴을 컴파일 합니다.올바르게 사용하려면 다음 절차를 따릅니다.
import java.util.regex.Pattern;
/**
* @author Rastislav Komara
*/
public class NaturalNumberChecker {
public static final Pattern PATTERN = Pattern.compile("^\\d+$");
boolean isNaturalNumber(CharSequence input) {
return input != null && PATTERN.matcher(input).matches();
}
}
guava 버전은 다음과 같습니다.
import com.google.common.primitives.Ints;
Integer intValue = Ints.tryParse(stringValue);
문자열 해석에 실패하면 예외를 발생시키는 대신 null을 반환합니다.
랠리 25rs 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
이것은 짧지만 짧은 것이 반드시 좋은 것은 아닙니다(또한 Danatel의 코멘트에서 지적된 것처럼 범위를 벗어난 정수 값을 잡는 것은 아닙니다).
input.matches("^-?\\d+$");
구현은 , 보다 앞서기 이 가지고 있는 것 것 .Exception
rather가 ratherNumberFormatException
를 참조해 주세요.
문자열 클래스의 matchs 메서드를 사용할 수 있습니다.[0-9]는 사용할 수 있는 모든 값을 나타냅니다.+는 1자 이상, *는 0자 이상일 수 있음을 의미합니다.
boolean isNumeric = yourString.matches("[0-9]+"); // 1 or more characters long, numbers only
boolean isNumeric = yourString.matches("[0-9]*"); // 0 or more characters long, numbers only
그럼 어떻게 해?
return Pattern.matches("-?\\d+", input);
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
번호만 확인하시면 됩니다.Format Exception : -
String value="123";
try
{
int s=Integer.parseInt(any_int_val);
// do something when integer values comes
}
catch(NumberFormatException nfe)
{
// do something when string values comes
}
문자열 배열에 순수 정수 및 문자열이 포함되어 있는 경우 다음 코드가 작동합니다.첫 글자만 보면 됩니다. 예: ["4", "44", "abc", "77", "bond"]
if (Character.isDigit(string.charAt(0))) {
//Do something with int
}
스캐너 클래스를 사용하여 hasNextInt()를 사용할 수도 있습니다.이것에 의해, 플로트등의 다른 타입도 테스트할 수 있습니다.
다른 옵션:
private boolean isNumber(String s) {
boolean isNumber = true;
for (char c : s.toCharArray()) {
isNumber = isNumber && Character.isDigit(c);
}
return isNumber;
}
문자열이 int 타입에 맞는 정수를 나타내는지 확인하고 싶다면 jonas의 답변을 약간 수정하여 Integer보다 큰 정수를 나타내도록 했습니다.MAX_VALUE이거나 정수보다 작습니다.MIN_VALUE는 false를 반환합니다.예를 들어 "3147483647"은 3147483647이 2147483647보다 크기 때문에 false를 반환하고 마찬가지로 "-2147483649"도 -2147483649보다 작기 때문에 false를 반환합니다.
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;
}
Apache Utils를 사용해 보십시오.
NumberUtils.isCreatable(myText)
사용 사례도 고려해야 합니다.
대부분의 경우 숫자가 유효할 것으로 예상되는 경우 예외를 검출하면 비활성 번호 변환을 시도할 때 성능 오버헤드만 발생합니다., 일부의 을 발신하고 있습니다.isInteger()
합니다.Integer.parseInt()
는 항상 유효한 숫자의 퍼포먼스 오버헤드를 발생시킵니다.문자열은 체크와 변환에 의해2회 해석됩니다.
이것은 문자열이 정수로 캐스팅될 수 있는 범위 내에 있는지 확인하는 Jonas의 코드를 수정한 것입니다.
public static boolean isInteger(String str) {
if (str == null) {
return false;
}
int length = str.length();
int i = 0;
// set the length and value for highest positive int or lowest negative int
int maxlength = 10;
String maxnum = String.valueOf(Integer.MAX_VALUE);
if (str.charAt(0) == '-') {
maxlength = 11;
i = 1;
maxnum = String.valueOf(Integer.MIN_VALUE);
}
// verify digit length does not exceed int range
if (length > maxlength) {
return false;
}
// verify that all characters are numbers
if (maxlength == 11 && length == 1) {
return false;
}
for (int num = i; num < length; num++) {
char c = str.charAt(num);
if (c < '0' || c > '9') {
return false;
}
}
// verify that number value is within int range
if (length == maxlength) {
for (; i < length; i++) {
if (str.charAt(i) < maxnum.charAt(i)) {
return true;
}
else if (str.charAt(i) > maxnum.charAt(i)) {
return false;
}
}
}
return true;
}
Android API를 사용하는 경우 다음을 사용할 수 있습니다.
TextUtils.isDigitsOnly(str);
항상 하게 구문 분석할 수 있기 때문에 생각합니다.아래에서 보시는 것처럼 항상 안전하게 해석할 수 있습니다.int
로로 합니다.String
그 반대도 아니구요.
그래서:
문자열 내의 모든 문자 슬롯이 문자 {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"} 중 하나 이상과 일치하는지 확인합니다.
if(aString.substring(j, j+1).equals(String.valueOf(i)))
위의 문자의 슬롯에서 발생한 모든 회수를 집계합니다.
digits++;
마지막으로 정수를 문자로 표시한 시간이 지정된 문자열의 길이와 동일한지 확인합니다.
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
단, 이 경우 String에서 (도트)는 1개뿐입니다.물론 체크하겠습니다.digits == (aString.length()-1)
여기서도 구문 분석 예외가 발생할 위험은 없습니다.단, 숫자(int 데이터 유형 등)를 포함하는 기존의 문자열을 구문 분석할 계획이라면 먼저 해당 문자열이 데이터 유형에 적합한지 확인해야 합니다.그렇지 않으면 캐스팅해야 합니다.
내가 도와주고 싶었다.
당신이 한 일은 효과가 있지만, 항상 그런 식으로 확인해서는 안 될 거예요.예외 처리는 "예외적인" 상황(예외적인 경우)을 위해 예약해야 하며 성능 측면에서 매우 비용이 많이 듭니다.
이것은 양의 정수에 대해서만 작동합니다.
public static boolean isInt(String str) {
if (str != null && str.length() != 0) {
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) return false;
}
}
return true;
}
난 이거면 돼.단순히 문자열이 원시인지 숫자인지 식별하기 위해 사용됩니다.
private boolean isPrimitive(String value){
boolean status=true;
if(value.length()<1)
return false;
for(int i = 0;i<value.length();i++){
char c=value.charAt(i);
if(Character.isDigit(c) || c=='.'){
}else{
status=false;
break;
}
}
return status;
}
모든 int 문자를 확인하려면 , 더블 네거티브를 사용합니다.
(!searchString.matches("[^0-9]+$")의 경우)...
[^0-9]+$는 정수가 아닌 문자가 있는지 확인하기 위해 true이면 테스트가 실패합니다.그렇지 않으면 성공이 실현됩니다.
여기서 많은 답변을 보았지만, 대부분은 문자열이 숫자인지 아닌지는 판단할 수 있지만 숫자가 정수 범위 내에 있는지 여부를 확인하지 못했습니다.
그래서 저는 다음과 같은 목적을 가지고 있습니다.
public static boolean isInteger(String str) {
if (str == null || str.isEmpty()) {
return false;
}
try {
long value = Long.valueOf(str);
return value >= -2147483648 && value <= 2147483647;
} catch (Exception ex) {
return false;
}
}
퍼포먼스보다 설명이 중요한 경우
특정 솔루션이 얼마나 효율적인지에 초점을 맞춘 많은 논의를 볼 수 있었지만, 문자열이 정수가 아닌 이유에 대한 논의는 없었다.또한, 모든 사람들은 숫자 "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 메서드는 좋아하지 않습니다.Integer.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
약간 수정됨(반환 false를 수반하는 srow):
이 기능은 성능이 우수하고 올바른 결과를 얻을 수 있습니다.
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;
}
언급URL : https://stackoverflow.com/questions/237159/whats-the-best-way-to-check-if-a-string-represents-an-integer-in-java
'programing' 카테고리의 다른 글
자바에서의 다운캐스트 (0) | 2022.08.28 |
---|---|
키스토어 파일에서 인증서 이름과 별칭을 확인하는 방법 (0) | 2022.08.28 |
JVM에서 사용하도록 프록시를 설정하려면 어떻게 해야 합니까? (0) | 2022.08.28 |
지시문에 데이터를 전달하시겠습니까? (0) | 2022.08.28 |
컴파일러는 다른 유형의 루프에 비해 do-while 루프에 대해 더 나은 코드를 생성합니까? (0) | 2022.08.28 |