在java中查找字符串中单词的开始和结束位置

时间:2015-01-13 15:49:18

标签: java regex string substring

找到"子串的开始和结束位置的最佳方法是什么?在一个句子?

例如对于句子"This is my first program",通过提供子字符串"my first"它应该返回start position=2end position=4

3 个答案:

答案 0 :(得分:6)

只需两步即可获得句子中单词的起始位置和结束位置。

public String startEndPosition(String sentence, String word) {
    int startingPosition = sentence.indexOf(word);
    int endingPosition = startingPosition + word.length();
    return "start position=" + startingPosition + " end position=" + endingPosition;
}
  • 方法indexOf将为您提供句子中单词的起始位置。

  • 使用起始位置添加单词的长度将为您提供句子中单词的结束位置。

答案 1 :(得分:1)

以下代码可以解决问题。该算法通过查找子串的第一个出现的索引来工作。

子字符串的起始索引等于子字符串之前出现的字数。我们可以通过在第一次匹配单词之前拆分字符串并计算单词数来找到这个数量。结束索引是由子字符串中的单词数增加的起始索引。

public static Range find(String string, String substring) {
    int index = string.indexOf(substring);
    if (index < 0)
        throw new IllegalStateException();
    int start = string.substring(0,index).split(" +").length;
    int end = start + substring.split(" +").length;
    return new Range(start, end);
}

public class Range {
    public final int start;
    public final int end;

    public Range(int start, int end) { this.start = start; this.end = end; };

    @Override
    public String toString() {
        return String.format("start position=%d end position=%d", start, end);
    }
}

示例代码:

System.out.println(find("This is my first program", "my first"));

输出:

start position=2 end position=4

答案 2 :(得分:0)

这应该可以正常工作:

public static void main(String args[])
{
    String[] sentence = "This is my first program".split(" ");
    String[] words = "my first".split(" ");

    int start = -1;

    for (int i = 0, j = 0; i < sentence.length && j < words.length; i++) {
        if (sentence[i].equals(words[j])) {
            if (j++ == 0)
                start = i;
        } else {
            start = -1;
            j = 0;
        }
    }

    if (start == -1)
        System.out.println("doesnt' match");
    else
        System.out.println(start + " - " + (start + words.length));
}
相关问题