gpt4 book ai didi

java - 获取字符串中某个位置周围的单词

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:12:03 25 4
gpt4 key购买 nike

我想获取字符串中某个位置周围的单词。例如后两个词和前两个词。

例如考虑字符串:

String str = "Hello my name is John and I like to go fishing and hiking I have two sisters and one brother.";
String find = "I";

for (int index = str.indexOf("I"); index >= 0; index = str.indexOf("I", index + 1))
{
System.out.println(index);
}

这会写出单词“I”所在位置的索引。但我希望能够获得围绕这些位置的单词的子串。

我希望能够打印出“John and I like to”和“and hiking I have two”。

不仅应该能够选择单个单词字符串。搜索“John and”将返回“name is John and I like”。

有什么简洁、聪明的方法可以做到这一点吗?

最佳答案

单个词:

您可以使用 String's split() method 实现这一目标.这个解决方案是O(n)

public static void main(String[] args) {
String str = "Hello my name is John and I like to go fishing and "+
"hiking I have two sisters and one brother.";
String find = "I";

String[] sp = str.split(" +"); // "+" for multiple spaces
for (int i = 2; i < sp.length; i++) {
if (sp[i].equals(find)) {
// have to check for ArrayIndexOutOfBoundsException
String surr = (i-2 > 0 ? sp[i-2]+" " : "") +
(i-1 > 0 ? sp[i-1]+" " : "") +
sp[i] +
(i+1 < sp.length ? " "+sp[i+1] : "") +
(i+2 < sp.length ? " "+sp[i+2] : "");
System.out.println(surr);
}
}
}

输出:

John and I like to
and hiking I have two

多词:

find 是一个多词时,Regex 是一个很好的干净的解决方案。但是,由于其性质,它会错过 周围的单词也匹配 find 的情况(参见下面的示例)。

下面的算法处理所有情况(所有解决方案的空间)。请记住,由于问题的性质,最坏情况下的解决方案是 O(n*m) (n str 的长度和 mfind 的长度)

public static void main(String[] args) {
String str = "Hello my name is John and John and I like to go...";
String find = "John and";

String[] sp = str.split(" +"); // "+" for multiple spaces

String[] spMulti = find.split(" +"); // "+" for multiple spaces
for (int i = 2; i < sp.length; i++) {
int j = 0;
while (j < spMulti.length && i+j < sp.length
&& sp[i+j].equals(spMulti[j])) {
j++;
}
if (j == spMulti.length) { // found spMulti entirely
StringBuilder surr = new StringBuilder();
if (i-2 > 0){ surr.append(sp[i-2]); surr.append(" "); }
if (i-1 > 0){ surr.append(sp[i-1]); surr.append(" "); }
for (int k = 0; k < spMulti.length; k++) {
if (k > 0){ surr.append(" "); }
surr.append(sp[i+k]);
}
if (i+spMulti.length < sp.length) {
surr.append(" ");
surr.append(sp[i+spMulti.length]);
}
if (i+spMulti.length+1 < sp.length) {
surr.append(" ");
surr.append(sp[i+spMulti.length+1]);
}
System.out.println(surr.toString());
}
}
}

输出:

name is John and John and
John and John and I like

关于java - 获取字符串中某个位置周围的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16387989/

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