Converting a StringBuilder To Integer Values In Java [duplicate]

荒凉一梦 提交于 2019-12-04 22:10:21

Try to split that string like:

String[] numbers = sb.toString().split(" ");//if spaces are uneven, use \\s+ instead of " "
for (String number : numbers) {
    list.add(Integer.valueOf(number));
}

Well my solution may not be the best here ,

From your question , what i've understood is that basically you want to get all the numbers from a string builder and put it in an integer array.

So here goes ,

Firstly you may want to get a string from the string builder.

String myString = mystringbuilder.toString();

This string now contains your numbers with spaces.

now use the following ,

String[] stringIntegers = myString.split(" "); // " " is a delimiter , a space in your case

This string array now contains your integers at positions starting from 0 .

Now , you may want to take this string array and parse its values and put it in an ArrayList.

This is how it's done ,

ArrayList<Integer> myIntegers = new ArrayList<Integer>();    
for(int i = 0; i<stringIntegers.length;i++){
myIntegers.add(Integer.parseInt(stringIntegers[i]));
}

now your myIntegers arraylist is populated with the needed integers , let me break it down for you.

  1. You create an array for the integers.
  2. There's a for loop to cycle through the string array
  3. In this for loop for every position of the string array you convert the string at that position to an integer with Integer.parseInt(String);
  4. Then , you just add it to the arraylist we created.

COMPLETE CODE:

String mynumbers = stringBuilder.toString();
String[] stringIntegers = mynumbers.split(" ");
ArrayList<Integer> myIntegers = new ArrayList<Integer>();
for(int i=0;i<stringIntegers.length;i++){
myIntegers.add(Integer.parseInt(stringIntegers[i]));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!