0

我有一个字符串

[Ian Wood P. M. Visscher]
[Ian Wood L. Mengersen]
[Ian Wood]
[P. M. Visscher Ian Wood].

我想将此字符串写入二维数组。(即)字符串

a[0][0]=Ian Wood ,
a[0][1]=P. M. Visscher,
a[1][0]=Ian Wood,
a[1][1]=L. Mengersen and so on.

每次我要输入时,字符串中的名称都会改变。如何将其拆分并以上述形式存储在数组中。请提出任何想法。在此先感谢。以下是我处理的代码,但没有正确拆分。

String[] parts = output.split(" ");
String[][] table = new String[parts.length / 2][2];
for (int i = 0, r = 0; r < table.length; r++) {
table[r][0] = parts[i++];
table[r][1] = parts[i++];
}
System.out.println(java.util.Arrays.deepToString(table));
4

1 回答 1

0

我假设您的意思是首字母为“某些分隔符”,并且您的输入字符串是一个字符串数组:

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

import static java.lang.System.out;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static java.util.regex.Pattern.compile;

public final class Q14914678 {

    private static final Pattern pattern = compile("^\\s*((?:[a-z]+\\s*?)*)\\s*([a-z]\\..*)?", CASE_INSENSITIVE);

    private static final String[] names = {
            "Ian Wood P. M. Visscher",
            "Ian Wood L. Mengersen",
            "Ian Wood",
            "P. M. Visscher Ian Wood"
    };

    public static void main(String[] args) {
        final List<String[]> collected = new ArrayList<String[]>();
        for ( final String name : names ) {
            final Matcher matcher = pattern.matcher(name);
            if ( matcher.matches() ) {
                collected.add(new String[] {matcher.group(1), matcher.group(2)});
            }
        }
        for ( final String[] array : pairArray ) {
            out.println(array[0] + " / " + array[1]);
        }
    }

}

结果如下:

Ian Wood / P. M. Visscher
Ian Wood / L. Mengersen
Ian Wood / null
 / P. M. Visscher Ian Wood
于 2013-02-16T21:25:06.670 回答