对于“狗”,我如何区分一个字符串--“懒散狗跑得快”,这样我就得到了Strings ="The Lazy",“狗”,"is running“?在Java中
我使用的代码是字符串str=:“懒惰的狗像狗一样跑”;字符串dog=“狗”;String[] strArr= str.split(狗);for(int i=0;i )
它会返回:懒惰者运行起来就像
发布于 2013-11-06 04:04:55
我建议使用正则表达式 (和分组)。正则表达式可以用来匹配几乎任何你想要的东西!
例如:
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);
}
}发布于 2013-11-06 04:05:51
我希望我正确地理解了你的问题,如果是这样的话,我将如何开始它,你仍然需要填补空白的边缘案例。您可以使用substring和indexOf来代替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]};
}
}https://stackoverflow.com/questions/19803733
复制相似问题