一个字:
您可以使用String
'ssplit()
方法来实现。这个解决方案是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
多词的情况。但是,由于其性质,它会忽略周围单词也匹配find
的情况(请参见下面的示例)。
下面的算法处理所有情况(所有解决方案的空间)。请记住,由于问题的性质,这个解决方案在最坏的情况下是O(n*m) (with n
being str
's length 和m
being find
's length)。
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