如何将字符串说“懒惰的狗跑得快”与“狗”分开,以便我得到字符串 =“懒惰”、“狗”、“跑得快”?在爪哇
我正在使用的代码 String str="懒狗像狗一样奔跑"; 字符串狗=“狗”;String[] strArr= str.split(dog); for(int i=0;i
它返回:懒惰的人正在像一个
如何将字符串说“懒惰的狗跑得快”与“狗”分开,以便我得到字符串 =“懒惰”、“狗”、“跑得快”?在爪哇
我正在使用的代码 String str="懒狗像狗一样奔跑"; 字符串狗=“狗”;String[] strArr= str.split(dog); for(int i=0;i
它返回:懒惰的人正在像一个
我建议使用正则表达式(和分组)。正则表达式几乎可以用来匹配你想要的任何东西!
例如
import java.util.regex.*;
public class PatternExample {
public static void main(String[] args) {
String split = "The Lazy dog is running fast";
Pattern pattern = Pattern.compile("(.*)(dog)(.*)");
Matcher matcher = pattern.matcher(split);
while (matcher.find()) {
for (int i = 0; i <= matcher.groupCount(); i++){
System.out.println(i + "->" + matcher.group(i));
}
}
}
}
给出:
0->The Lazy dog is running fast
1->The Lazy
2->dog
3-> is running fast
采取2:没有正则表达式
public class PatternExample {
public static void main(String[] args) {
String split = "The Lazy dog is running fast";
String word = "dog";
String tmp = split;
while (tmp.contains(word)){
int x = tmp.indexOf(word);
System.out.println(tmp.substring(0,x));
System.out.println(word);
tmp = tmp.substring(x+word.length());
}
System.out.println(tmp);
}
}
我希望我正确理解了您的问题,如果是这样,这就是我将如何开始,您仍然需要填补边缘情况的空白。可以用substring
andindexOf
代替split
,但不使用似乎太方便了。
package test;
public class Main {
public static void main(String[] args) {
String sentence = "The Lazy dog is running fast";
String word = "dog";
String[] splitByWord = splitByWord(word, sentence);
for (String string : splitByWord) {
System.out.println(string);
}
}
public static String[] splitByWord(String word, String sentence) {
String[] split = sentence.split(" " + word + " ");
//TODO: handle edge cases where word is not found in sentence, or first word, or last
return new String[]{split[0], word, split[1]};
}
}