How can I convert the string to Integers and how can I create an ArrayList with these integers?
My String contains only numbers and there is a gap between my numbers.
For example, given the string st1 = "1 2 3 4" or str2 = "11 20 23 24".
I need an ArrayList for str1 like "1, 2, 3, 4"
I tried to use Integer.parseInt(str1) and Integer.valueOf(str1) but these work for such as str1 = "1234"
3 Answers
This method will convert such strings to an ArrayList<Integer>:
public static ArrayList<Integer> toStringList(String string){
String ints[]=string.split(" ");
ArrayList<Integer> list=new ArrayList<>();
for(String str:ints){
list.add(Integer.parseInt(str));
}
}
Remember this method will convert your string such as "1 2 3 4" to a list with 1 to 4 values. If you want to convert it to 1234 you should first remove the spaces:
String str="1 2 3 4 ";
str = str.replaceAll(" ","");
Integer number=Integer.parseInt(str); //equals 1234
3 Comments
Scary Wombat
Better to use
replace as this is not using regex str = str.replace(" ","");buyufix
Thank you, the first answered my question and it works. How can I do that without using
String ints[]=string.split(" "); , so in a way, without using array?Omid.N
If you want the numbers to be seperate you have to split the string
This code will convert any number found within the string to its integer. This will solve your problem.
String str = "1 2 3 4 5 11 12 13 14 15 1 12 123 1234 12345";
int stringLength = str.length();
int[] answer;
String intBuffer = "";
int j = 0, countSpaces = 0;
for (int i = 0; i < stringLength; i++) {
if (str.charAt(i) == ' ') countSpaces++;
}
answer = new int[countSpaces + 1];
for (int i = 0; i < stringLength; i++) {
if (str.charAt(i) != ' ') {
intBuffer = intBuffer + str.charAt(i);
if (i == stringLength - 1)
answer[j] = Integer.parseInt(intBuffer);
} else {
answer[j++] = Integer.parseInt(intBuffer);
intBuffer = "";
}
}
for (int i = 0; i < answer.length; i++)
System.out.println(answer[i] + " ");
st1 = "1 2 3 4"tost1 = "1234"first?