如何从Java中的String中提取多个整数?

子昂 *_*昂 陳 0 java string int type-conversion

我得到了一系列的字符串"(123, 234; 345, 456) (567, 788; 899, 900)".如何将这些数字提取到数组中aArray[0]=123, aArray=[234], ....aArray[8]=900;

谢谢

Mad*_*mer 5

这可能过于复杂,但干草...

我们需要做的第一件事是删除我们不需要的所有废话......

String[] crap = {"(", ")", ",", ";"};
String text = "(123, 234; 345, 456) (567, 788; 899, 900)";
for (String replace : crap) {
    text = text.replace(replace, " ").trim();
}
// This replaces any multiple spaces with a single space
while (text.contains("  ")) {
    text = text.replace("  ", " ");
}
Run Code Online (Sandbox Code Playgroud)

接下来,我们需要将字符串的各个元素分成一个更易于管理的形式

String[] values = text.split(" ");
Run Code Online (Sandbox Code Playgroud)

接下来,我们需要将每个String值转换为int

int[] iValues = new int[values.length];
for (int index = 0; index < values.length; index++) {

    String sValue = values[index];
    iValues[index] = Integer.parseInt(values[index].trim());

}
Run Code Online (Sandbox Code Playgroud)

然后我们显示值......

for (int value : iValues) {
    System.out.println(value);
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*eón 5

策略:找到一个或多个数字在一起,通过正则表达式加入到一个列表中。

代码:

    LinkedList<String> list = new LinkedList<>();
    Matcher matcher = Pattern.compile("\\d+").matcher("(123, 234; 345, 456) (567, 788; 899, 900)");
    while (matcher.find()) {
        list.add(matcher.group());
    }
    String[] array = list.toArray(new String[list.size()]);
    System.out.println(Arrays.toString(array));
Run Code Online (Sandbox Code Playgroud)

输出:

[123, 234, 345, 456, 567, 788, 899, 900]
Run Code Online (Sandbox Code Playgroud)


dam*_*zam 5

你几乎肯定看过这句话:

有些人在遇到问题时会想“我知道,我会使用正则表达式”。现在他们有两个问题。

但是正则表达式确实是这类事情的朋友。

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Numbers {
    public static void main(String[] args) {
        String s = "(123, 234; 345, 456) (567, 788; 899, 900)";
        Matcher m = Pattern.compile("\\d+").matcher(s);
        List<Integer> numbers = new ArrayList<Integer>();
        while(m.find()) {
            numbers.add(Integer.parseInt(m.group()));
        }
        System.out.println(numbers);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

[123, 234, 345, 456, 567, 788, 899, 900]
Run Code Online (Sandbox Code Playgroud)