在 Java 中将 StringBuilder 转换为整数值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29717963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting a StringBuilder To Integer Values In Java
提问by doppler
Well the question is very simple. Lets say there is a StringBuilder sb
Inside of sb numbers like this:
那么问题很简单。假设有一个StringBuilder sb
像这样的Inside of sb numbers:
"25 9631 12 1895413 1 234564"
"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!
如何一一获取这些数字并将它们初始化为一个ArrayList<Integer> list
或更具体的数字是否可能?感谢检查!
采纳答案by SMA
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));
}
回答by TheAnimatrix
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 .
这个字符串数组现在包含从 0 开始的位置的整数。
Now , you may want to take this string array and parse its values and put it in an ArrayList.
现在,您可能想要获取这个字符串数组并解析其值并将其放入一个 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.
现在,您的 myIntegers 数组列表中已填充了所需的整数,让我为您分解一下。
- You create an array for the integers.
- There's a for loop to cycle through the string array
- 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);
- Then , you just add it to the arraylist we created.
- 您为整数创建一个数组。
- 有一个 for 循环来循环遍历字符串数组
- 在这个字符串数组的每个位置的 for 循环中,您可以使用 Integer.parseInt(String); 将该位置的字符串转换为整数;
- 然后,您只需将其添加到我们创建的数组列表中即可。
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]));
}