根据搜索到的单词和起始位置从句子中捕获前一个单词和下一个单词

时间:2016-03-10 08:17:54

标签: java regex string

我想根据搜索到的单词及其起始位置(字符串中搜索到的单词的字符索引,从0开始)检索搜索单词的前一个单词和下一个单词java中的字符串 例如,如果我有一个字符串如下:

I am a teacher and a father.

如果给出搜索的字词是: a
和他的起始位置: 4
输出应为:

am a teacher

如果给出搜索的单词是: a
和他的开始职位: 18
输出应为:

and a father   

任何想法?
编辑:请记住,我需要使用起始位置,因为字符串中可能有重复的单词。

2 个答案:

答案 0 :(得分:0)

public String searchedWordContext(String sentence, String searchedWord) {
    if (sentence == null || searchedWord == null) throw new IllegalArgumentException("May not be null");
    String[] words = sentence.split(" ");
    int searchedIndex = -1;
    for (int i=0; i<words.length; i++) {
        if (words[i].equals(searchedWord)) searchedIndex = i;
        // first occurence - abort
        if (searchedIndex!=-1) break;
    }
    if (searchedIndex == -1) throw new IllegalArgumentException("Searched word: " + searchedWord + " not found in sentence: " + sentence);
    if (words.length < 2) return searchedWord;
    if (searchedIndex == 0) return words[searchedIndex] + " "+ words[serchedIndex+1];
    if (searchedIndex == words.length) return words[searchedIndex-1] + " "+ words[searchedIndex];
    return words[searchedIndex-1] + " " + words[searchedIndex] + " " + words[searchedIndex+1];
}

答案 1 :(得分:0)

public String queryExamples(String sentence,int selectedPosition) {
    StringBuffer queries = new StringBuffer();
    if (selectedPosition > sentence.length()) {
    throw new IllegalArgumentException("The selected position must be less than sentence length.");
        }
        String[] afterWords = sentence.substring(selectedPosition).split(" ");
        String afterWord = "";
        String beforeWord = "";
        if (afterWords.length == 1) {
            afterWord = "";
        } else {
            afterWord = afterWords[1];
        }

        if(selectedPosition==0){
            beforeWord = "";
        } else {
            String[] WordList = sentence.substring(0, selectedPosition).split(" ");
            if (WordList.length > 0) {
                beforeWord = WordList[WordList.length - 1];
            }
        }
        queries.append(beforeWord).append(" ").append(afterWord);

    }

    return queries;
}