Converting a StringBuilder To Integer Values In Java [duplicate]

六月ゝ 毕业季﹏ 提交于 2019-12-10 00:34:33

问题


Well the question is very simple. Lets say there is a StringBuilder sb Inside of sb numbers like this:

"25 9631 12 1895413 1 234564"

How to get those numbers one by one and initialize them into an ArrayList<Integer> list or to be more specific is it possible? Thanks for checking!


回答1:


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));
}



回答2:


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]));
}


来源:https://stackoverflow.com/questions/29717963/converting-a-stringbuilder-to-integer-values-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!