Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a String with spaces to an Integer in java

I'm trying to convert a String variable into an integer, only the String looks like this (for example):

String string = " 12";

And so the String has a space in front of it. Now the String variable is being read from a .txt file which is why I'm having the issue of having the space in front of it. I need to convert the variable into an int, but when I try:

int integer = Integer.parseInt(string);

to pass the String into an integer, it compiles but I get an error when trying to run the program, since there is white space as part of the String.

Is there a way to pass a String of numbers with a space in front of it into an int? Would .trim work? And if so, how would I use that? (I'm not very familiar with .trim, I'm still learning!!) I appreciate the help! ^_^

like image 200
k1234 Avatar asked May 25 '14 03:05

k1234


People also ask

Does parseInt remove spaces?

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

How do you number spaces in Java?

getPosition(); String formatter = "%1"+position+"s%2$s\n"; System. out. format(formatter, "", node. element);


2 Answers

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());
like image 67
Masudul Avatar answered Sep 18 '22 13:09

Masudul


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());
like image 37
Josh Engelsma Avatar answered Sep 21 '22 13:09

Josh Engelsma