如何从Java中的String中提取多个整数? [英] How to extract multiple integers from a String in Java?

查看:158
本文介绍了如何从Java中的String中提取多个整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I got a series of string like "(123, 234; 345, 456) (567, 788; 899, 900)". How to a extract those numbers into an array like aArray[0]=123, aArray=[234], ....aArray[8]=900;

谢谢

推荐答案

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

This is probably overly convoluted, but hay...

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

The first thing we need to do is remove all the crap we don't need...

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("  ", " ");
}

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

Next, we need to seperate the individual elements of the string into a more manageable form

String[] values = text.split(" ");

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

Next, we need to convert each String value to an 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());

}

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

Then we display the values...

for (int value : iValues) {
    System.out.println(value);
}

这篇关于如何从Java中的String中提取多个整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆