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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12721261/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:58:08  来源:igfitidea点击:

How to extract multiple integers from a String in Java?

javastringinttype-conversion

提问by u1696056

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;

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

Thank you

谢谢

回答by MadProgrammer

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

Next, we need to convert each Stringvalue to an int

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

}

Then we display the values...

然后我们显示值...

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

回答by Daniel De León

Strategy:Find one or more numbers that are together, through a regular expression to be added to a list.

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

Code:

代码:

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

Output:

输出:

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

回答by damzam

You've almost certainly seen the quote:

你几乎肯定看过这句话:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

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

But regular expressions really are your friend for this sort of thing.

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

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

Outputs:

输出:

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

回答by Abubakkar

Iterate through each character and store numbers in a temporary array until you find a character(like ,, ;) then store the data from temporary array into your array and then empty that temporary array for next use.

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

回答by npinti

Since your numbers are separated by a specific set of characters, you can take a look at the .split(String regex)method.

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

回答by svz

As there may be a number of different delimeters in your string, you can go through it and replace all non-digit characters with spaces. Then you can use split("\\s")to split your string into an array of substrings with numbers. And finally convert them to numbers.

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

回答by icza

This method will extract integers from a given string. It also processes strings where other characters are used to separate numbers, not just the ones in your example:

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

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

Note:Since the internal forloop positions after an integer and the outside forloop will increase the ivariable when searching for the next integer, the algorithm will require at least one character to separate the integers but I think this is desirable. For example the "-23-12"source will produce the numbers [ -23, 12 ]and NOT [ -23, -12 ](but "-23 -12"will produce [ -23, -12 ] as expected).

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

回答by Wizart

The simplest approach is to use of combination of String.indexOf()(or something like this) and NumberFormat.parse(ParsePosition)methods. An algorithm would be following:

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

  1. start from the beginning of string
  2. find a number starting from that position
  3. parse using mentioned method of NumberFormat which will stop on non-digit character and return a value
  4. repeat 2) starting from that position (until end of string is reached)
  1. 从字符串的开头开始
  2. 找到一个从那个位置开始的数字
  3. 使用提到的 NumberFormat 方法进行解析,该方法将在非数字字符上停止并返回一个值
  4. 重复 2) 从该位置开始(直到到达字符串末尾)

At the same time, the string has a particular structure, so IMHO some parser would be better approach as it would also check a correctness of format (if it's necessary, I don't know). There are a lot of tools for generating Java code from a description of a grammar (like ANTLR, etc.). But it might be too complex solution for the case.

同时,字符串具有特定的结构,因此恕我直言,某些解析器会是更好的方法,因为它还会检查格式的正确性(如果有必要,我不知道)。有很多工具可以根据语法的描述(如 ANTLR 等)生成 Java 代码。但对于这种情况,它可能是太复杂的解决方案。

回答by u1696056

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

Above code will return a string "0123023403540456"

上面的代码将返回一个字符串“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));
}

and it will get [123, 234, 345, 456]

它会得到 [123, 234, 345, 456]

回答by Sujay

I think you can use regular expression to get your result. Something like this maybe:

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

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