gpt4 book ai didi

java - 从字符串中查找单词的下一个单词

转载 作者:行者123 更新时间:2023-11-29 04:09:33 25 4
gpt4 key购买 nike

我编写了以下代码来从 Java 字符串中获取下一个单词。我觉得它非常原始,我不应该为此编写这么多代码,但找不到任何其他方法。想知道是否有更好的方法可以做到这一点:

public static String getNextWord(String str, String word) {
String nextWord = null;
// to remove multi spaces with single space
str = str.trim().replaceAll(" +", " ");
int totalLength = str.length();
int wordStartIndex = str.indexOf(word);
if (wordStartIndex != -1) {
int startPos = wordStartIndex + word.length() + 1;
if (startPos < totalLength) {
int nextSpaceIndex = str.substring(startPos).indexOf(" ");
int endPos = 0;
if (nextSpaceIndex == -1) {
// we've reached end of string, no more space left
endPos = totalLength;
} else {
endPos = startPos + nextSpaceIndex;
}
nextWord = str.substring(startPos, endPos);
}
}
return nextWord;
}

注意:输入单词可以是任何内容(多个单词、单个单词、不在字符串中的单词等)。

测试:

    String text = "I am very happy with life";

System.out.println(StringUtil.getNextWord(text, "I"));
System.out.println(StringUtil.getNextWord(text, "I am"));
System.out.println(StringUtil.getNextWord(text, "life"));
System.out.println(StringUtil.getNextWord(text, "with"));
System.out.println(StringUtil.getNextWord(text, "fdasfasf"));
System.out.println(StringUtil.getNextWord(text, text));

输出:

am
very
null
life
null
null

最佳答案

这听起来像是正则表达式的工作。像这样的事情:

public static String getNextWord(String str, String word){
Pattern p = Pattern.compile(word+"\\W+(\\w+)");
Matcher m = p.matcher(str);
return m.find()? m.group(1):null;
}

关于java - 从字符串中查找单词的下一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55863995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com