Sean
Sean

Reputation: 1123

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 can I do to filter out the \n?

Thanks

Upvotes: 2

Views: 2259

Answers (3)

Stephen C
Stephen C

Reputation: 718956

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.

Upvotes: 2

psicopoo
psicopoo

Reputation: 1676

\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"

Upvotes: 4

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

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.

Upvotes: 2

Related Questions