In my limited experience, I worked on several projects that had some kind of class string class with methods to determine if a given string is a number. The idea was always the same, but the implementation was different. Some surround try parsing with try / catch
public boolean isInteger(String str) { try { Integer.parseInt(str); return true; } catch (NumberFormatException nfe) {} return false; }
and others match regular expression
public boolean isInteger(String str) { return str.matches("^-?[0-9]+(\\.[0-9]+)?$"); }
Is one of these methods better than the other? I personally prefer to use the regex approach, as it is concise, but will it be executed by the parameter, if called, iterating over, say, a list of several hundred thousand lines?
Note. Since Iโm new to the site, I donโt quite understand this business community of the Wiki, so if this applies to it, let me know and I will gladly translate it.
EDIT: With all TryParse suggestions, I put the Asaph comparison code (thanks for a great post!) In C # and added the TryParse method. And, as it seems, TryParse wins hands. However, the try catch approach took an insane amount of time. As far as I think, I did something wrong! I also updated the regex to handle negative and decimal points.
Results for updated C # code:
00:00:51.7390000 for isIntegerParseInt 00:00:03.9110000 for isIntegerRegex 00:00:00.3500000 for isIntegerTryParse
Using:
static bool isIntegerParseInt(string str) { try { int.Parse(str); return true; } catch (FormatException e){} return false; } static bool isIntegerRegex(string str) { return Regex.Match(str, "^-?[0-9]+(\\.[0-9]+)?$").Success; } static bool isIntegerTryParse(string str) { int bob; return Int32.TryParse(str, out bob); }
performance c #
thorncp Sep 02 '09 at 17:25 2009-09-02 17:25
source share