1

如果我有一个字符串:

String s = "This is a string to test splitting on!";

以及表示字符串中索引的整数数组:

int[] indices = {4, 6, 9, 12, 15};

是否有可能得到一个字符串数组,如:

"This",
" i",
"s a",
" st",
"rin",
"g to test splitting on!"

不循环调用s.substring(indices[i], indices[i+1])(或类似的)索引?

不幸的是,索引都是任意的,所以正则表达式无济于事。基本上我想找到一个等价的 split() 我可以传递一个整数数组而不是一个正则表达式。

4

1 回答 1

2

如果你不想使用 substring(),试试这个:

import java.util.*;
public class StringSplitter implements Iterable<String>
{
    private Scanner scanner;
    private StringBuilder toParse;
    private int indices[];

    public StringSplitter(String toSplit, int... indices)
    {
        Arrays.sort(indices);    //make sure it is sorted otherwise it won't work properly
        toParse = new StringBuffer(toSplit);
        for(int i = 0; i < indices.length; ++i)
        {
            toParse.insert(indices[i] + i, "\u0080");
        }
        scanner = new Scanner(toParse.toString());
        scanner.useDelimeter("\u0080");
        this.indices = indices;
    }

    public Iterator<String> iterator()
    {
        return scanner;
    }
}

然后使用for-each循环遍历字符串:

StringSplitter s = new StringSplitter("This is a string to test splitting on!", 4, 6, 9, 12, 15);
for(String elem : s)
{
    System.out.println(elem);
}
于 2013-03-13T06:34:08.993 回答