gpt4 book ai didi

java - 根据单词在java中拆分字符串

转载 作者:行者123 更新时间:2023-11-30 11:26:28 25 4
gpt4 key购买 nike

如何将字符串 say "The Lazy dog is running fast"与 "dog"分开,以便我得到字符串 ="The Lazy", "dog","is running fast"?在Java中

我正在使用的代码 String str="这只懒狗跑得像条狗"; 串狗=“狗”; String[] strArr= str.split(狗); 对于(int i = 0;我

它返回:懒人 运行得像一个

最佳答案

我建议使用 regular expressions (和分组)。正则表达式几乎可以用来匹配任何你想要的东西!

例如

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);
}
}

关于java - 根据单词在java中拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19803733/

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