开发者

converting string to int if string has other characters in it

Hi I have a string "72\n" When I try to use Integer.parseInt("72\n") it gives me a log error, unable to parse'72 ' as integer. What ca开发者_开发问答n I do to filter out the \n?

Thanks


\n is the newline character, which among other things is a type of whitespace. Strings in Java have a method called trim(), which returns a copy of the string with leading and trailing whitespace removed.

String a = "72\n";
String b = a.trim(); // "72"


replaceAll with an appropriate regex should work well. For instance \\D will find all non-numeric characters, and so myString.replaceAll("\\D", "") could work well:

  String test2 = "72\n";      
  System.out.printf("\"%s\"%n", test2);

  test2 = test2.replaceAll("\\D", "");
  System.out.printf("\"%s\"%n", test2);

This gets trickier if we allow for non-int floating point numbers which allow for locale dependent non-numeric chars such as a single . for a decimal point in the usa and , in some other locations.


The simple way to deal with leading and trailing whitespace is to use String.trim().

You could use replaceAll or similar to remove embedded whitepace and other "noise", but you run the risk of changing the user's intended meaning. For instance, an embedded space or comma might have meant that the user thought that he could / should enter multiple numbers. In my opinion, it is better to tell the user there is an error than it is to try to fix the error and get it wrong (from the user's perspective).

So, in this case I'd say that using replaceAll is not a good idea because it is liable to "fix" whitespace within the number as well as leading or trailing it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜