Convert.ToInt32 vs TryParse

We all know which effects can have many exceptions due to the performance of our applications, so we should avoid things like using exceptions for the control flow. After this statement, I must admit that when coding, I didn’t care what it was about. I mainly worked on the Java platform, but lately I did it on the .NET platform and just found this convenient method: public static bool TryParse(string s,out int result) which allows you to convert String to int without throwing an exception. From now on, I continue to use it. I just wanted to ask you about your preferences for using public static bool TryParse(string s,out int result)or public static int ToInt32(string value).

And from a Java point of view, just pointing out that it doesn’t have the same method, even though we could get it through things like:

boolean isInteger = Pattern.matches("^\d*$", myString);

Thanks.

+5
source share
5 answers

Yes, Java does not have a similar method, although without parameters it outis actually quite difficult to express (although it wants to return a primitive). Generally, in C # you should use TryParseif you expect that the value will sometimes not be integer, ToInt32otherwise; thus, an “exceptional” situation is considered as such.

, TryParse, , , . "" ( ) , .

+7

#, Java , , . , , , .

String.matches() Pattern.matches() ; , . Pattern, . 10 000 , 20% , , Integer.parseInt() .

, . , , , Integer.parseInt() . , , ^\d*$ - , "" , Integer.MAX_VALUE, .

+3

Java StringUtils ( commons-lang), isNumeric

, , :

public static boolean isNumeric(String str) {
  if (str == null) {
    return false;
  }
  int sz = str.length();
  for (int i = 0; i < sz; i++) {
    if (Character.isDigit(str.charAt(i)) == false) {
      return false;
    }
  }
  return true;
 }

, , . !

+1

Java, , , , , :

boolean isInteger = Pattern.matches("^\d*$", myString);

, Integer.parseInt(myString) , . -. , int 10 . , ^-?0*\d{1,10}$. , .

. . , , parseInt . :

static boolean wouldParseIntThrowException(String s) {
    if (s == null || s.length() == 0) {
        return true;
    }

    char[] max = Integer.toString(Integer.MAX_VALUE).toCharArray();
    int i = 0, j = 0, len = s.length();
    boolean maybeOutOfBounds = true;

    if (s.charAt(0) == '-') {
        if (len == 1) {
            return true; // s == "-"
        }
        i = 1;
        max[max.length - 1]++; // 2147483647 -> 2147483648
    }
    while (i < len && s.charAt(i) == '0') {
        i++;
    }
    if (max.length < len - i) {
        return true; // too long / out of bounds
    } else if (len - i < max.length) {
        maybeOutOfBounds = false;
    }
    while (i < len) {
        char digit = s.charAt(i++);
        if (digit < '0' || '9' < digit) {
            return true;
        } else if (maybeOutOfBounds) {
            char maxdigit = max[j++];
            if (maxdigit < digit) {
                return true; // out of bounds
            } else if (digit < maxdigit) {
                maybeOutOfBounds = false;
            }
        }
    }
    return false;
}

, . , .

#, , , TryParse. true, . , parseInt, null .

, , . :

private static Pattern QUITE_ACCURATE_INT_PATTERN = Pattern.compile("^-?0*\\d{1,10}$");

static Integer tryParseIntegerWhichProbablyResultsInOverflow(String s) {
    Integer result = null;
    if (!wouldParseIntThrowException(s)) {
        try {
            result = Integer.parseInt(s);
        } catch (NumberFormatException ignored) {
            // never happens
        }
    }
    return result;
}

static Integer tryParseIntegerWhichIsMostLikelyNotEvenNumeric(String s) {
    Integer result = null;
    if (s != null && s.length() > 0 && QUITE_ACCURATE_INT_PATTERN.matcher(s).find()) {
        try {
            result = Integer.parseInt(s);
        } catch (NumberFormatException ignored) {
        // only happens if the number is too big
        }
    }
    return result;
}

static Integer tryParseInteger(String s) {
    Integer result = null;
    if (s != null && s.length() > 0) {
        try {
            result = Integer.parseInt(s);
        } catch (NumberFormatException ignored) {
        }
    }
    return result;
}

static Integer tryParseIntegerWithoutAnyChecks(String s) {
    try {
        return Integer.parseInt(s);
    } catch (NumberFormatException ignored) {
    }
    return null;
}
+1

public static bool TryParse ( s, out int result) public static int ToInt32 ( ).

, TryParse, , , . , , . , ; TryParse .

Java, # . Java , NullPointerException NumberFormatException Number.ValueOf(...); , "" - . TryParse # .

0

All Articles