Converting a String with spaces to an Integer in java
Would .trim work? And if so, how would I use that?
Yes, trim()
will work, it will remove leading and trailing spaces from String
,
int integer = Integer.parseInt(string.trim());
The string split() method works well if you have a string of multiple numbers separated by spaces.
String numbers = "1 23 456";
String[] numbersArray = numbers.split(" "); // splitting string by spaces
System.out.println(numbersArray.toString());
// output ["1","23","456"]
Then you can use Integer.parseInt() on each index of the array. Hope that helps
Use the string trim function in Java to first get a string without the spaces, then parse it...
1.) Remove spaces with trim ... String#trim
String stringWithoutSpace = string.trim();
2.) Parse the string without spaces ... Integer#parseInt
int integer = Integer.parseInt(stringWithoutSpace);
3.) Do everything above in one step ...
int integer = Integer.parseInt(string.trim());
If you using Java 11, you can use the String::strip
method. For example:
int integer = Integer.parseInt(string.strip());
The strip()
method is similar to trim()
but uses Character.isWhitespace(int)
to resolve spaces. (The Character.isWhitespace(int)
method is Unicode-aware.)