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

时间:2012-10-04 06:09:59

标签: java string int type-conversion

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

这样的数组中

谢谢

11 个答案:

答案 0 :(得分: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("  ", " ");
}

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

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

接下来,我们需要将每个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());

}

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

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

答案 1 :(得分:4)

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

<强>代码:

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

<强>输出:

[123, 234, 345, 456, 567, 788, 899, 900]

答案 2 :(得分:4)

你几乎肯定看过这句话:

  

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

但是正则表达式确实是你的朋友。

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

输出:

[123, 234, 345, 456, 567, 788, 899, 900]

答案 3 :(得分:2)

遍历每个字符并将数字存储在临时数组中,直到找到一个字符(如,;),然后将临时数组中的数据存储到数组中,然后清空该临时数组下次使用。

答案 4 :(得分:0)

由于您的数字由一组特定字符分隔,因此您可以查看.split(String regex)方法。

答案 5 :(得分:0)

由于您的字符串中可能存在多个不同的分隔符,因此您可以使用spaces替换所有非数字字符。然后,您可以使用split("\\s")将字符串拆分为带有数字的子字符串数组。最后将它们转换为数字。

答案 6 :(得分:0)

此方法将从给定字符串中提取整数。它还处理字符串,其他字符用于分隔数字,而不仅仅是示例中的字符:

public static Integer[] extractIntegers( final String source ) {
    final int    length = source.length();
    final char[] chars  = source.toCharArray();

    final List< Integer > list = new ArrayList< Integer >();

    for ( int i = 0; i < length; i++ ) {

        // Find the start of an integer: it must be a digit or a sign character
        if ( chars[ i ] == '-' || chars[ i ] == '+' || Character.isDigit( chars[ i ] ) ) {
            final int start = i;

            // Find the end of the integer:
            for ( i++; i < length && Character.isDigit( chars[ i ] ); i++ )
                ;

            // Now extract this integer:
            list.add( Integer.valueOf( source.substring( start, i ) ) );
        }
    }

    return list.toArray( new Integer[ list.size() ] );
}

注意:由于内部for循环位于整数之后,外部for循环会在搜索下一个整数时增加i变量,算法将需要至少一个字符来分隔整数,但我认为这是可取的。例如,"-23-12"来源将生成数字[ -23, 12 ]而非[ -23, -12 ](但"-23 -12"将按预期生成[-23,-12]。

答案 7 :(得分:0)

最简单的方法是使用String.indexOf()(或类似的东西)和NumberFormat.parse(ParsePosition)方法的组合。算法如下:

  1. 从字符串的开头
  2. 开始
  3. 从该位置开始查找号码
  4. 使用提到的NumberFormat方法解析,该方法将停止在非数字上 字符并返回值
  5. 重复2)从该位置开始(直到到达字符串结尾)
  6. 同时,字符串有一个特定的结构,所以恕我直言一些解析器会更好的方法,因为它也会检查格式的正确性(如果有必要,我不知道)。有很多工具可以从语法描述中生成Java代码(比如ANTLR等)。但对于这个案子来说,这可能是一个过于复杂的解决方案。

答案 8 :(得分:0)

我认为您可以使用正则表达式来获得结果。这样的事情可能是:

String string = "(123, 234; 345, 456) (567, 788; 899, 900)";
String[] split = string.split("[^\\d]+");
int number; 
ArrayList<Integer> numberList = new ArrayList<Integer>();

for(int index = 0; index < split.length; index++){
    try{
        number = Integer.parseInt(split[index]);
        numberList.add(number);
    }catch(Exception exe){

    }
}

Integer[] numberArray = numberList.toArray(new Integer[numberList.size()]);
for(int index = 0; index < numberArray.length; index++){
    System.out.println(numberArray[index]);
}

答案 9 :(得分:0)

又一种方式。如果你想编写更少的代码可能会很好,如果你不能将libs添加到你的项目中可能会很糟糕

import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;

public static void main(String[] args) throws IOException {
        String text = "(123, 234; 345, 456) (567, 788; 899, 900)";
        Splitter splitter = Splitter.onPattern("[,;\\)\\(]").omitEmptyStrings();
        String[] cleanString = Iterables.toArray(splitter.split(text), String.class);

        System.out.println(Arrays.toString(cleanString));

    }
确保大师可以进一步清理它。

答案 10 :(得分:0)

 for (int i = 0; i < faces.total(); i++) 
 {
    CvRect r = new CvRect(cvGetSeqElem("(123, 234; 345, 456)", i));             
    String x=""+Integer.toString(r.x());
    String y=""+Integer.toString(r.y());
    String w=""+Integer.toString(r.width());
    String h=""+Integer.toString(r.height());
    for(int j=0;j<(4-Integer.toString(r.x()).length());j++)   x="0"+x;
    for(int j=0;j<(4-Integer.toString(r.y()).length());j++)   y="0"+y;
    for(int j=0;j<(4-Integer.toString(r.width()).length());j++)   w="0"+w;
    for(int j=0;j<(4-Integer.toString(r.height()).length());j++)   h="0"+h;
    r_return=""+x+y+w+h;
 }

上面的代码将返回一个字符串“0123023403540456”

int[] rectArray = new int[rectInfo.length()/4];
for(int i=0;i<rectInfo.length()/4; i++)
{
    rectArray[i]=Integer.valueOf(rectInfo.substring(i*4, i*4+4));
}

它将获得[123,234,345,456]