如何在Java中从字符串中提取多个整数?

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

5
我认为这样贬低问题并不好。提问者可能是编程新手,以为有一种神奇的方法可以解决这个问题。 - Haozhun
欢迎来到Stack Overflow!我们鼓励您研究问题。如果您已经尝试过某些解决方法,请将其添加到问题描述中 - 如果没有,请先进行研究和尝试,然后再提出问题。 - user647772
11个回答

6

可能有些复杂,但是我们需要做的第一件事就是删除我们不需要的所有内容...

首先,我们需要删除所有无用的东西...

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

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

输出:

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

1
这是我会做的事情。只有一件事需要注意。看着字符串的格式,Quoi先生可能想要一个不同的结构。它看起来像是一个包含对中的列表列表。List<List<Tupel<Integer, Integer>>> 可能吗?不过,我仍然会选择正则表达式的解决方案。 - Thobias Bergqvist
检查问题中所需数组的第8个元素。这给了我关于数组应该是什么样的线索。 ;) - Daniel De León
1
在 Stack Overflow 上,通常不欢迎仅仅是代码答案... - Coding Mash

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

输出:

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

有人真的在这个问题上给我的解决方案点了踩吗?为什么不留下评论来解释一下呢? - damzam

2

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


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 ])。


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

0

另一种方式。如果您想写更少的代码可能会很好,但如果您无法将库添加到项目中,则可能不太好。

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

    }

我相信专家们可以进一步优化它。


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]


0

由于您的数字是由特定字符分隔的,因此您可以查看{{link1:.split(String regex)}}方法。


0

由于您的字符串中可能会有许多不同的分隔符,因此可以遍历它并用空格替换所有非数字字符。然后,您可以使用split("\\s")将字符串拆分为数字子字符串数组。最后将它们转换为数字。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接