gpt4 book ai didi

java - 如何检查并显示其他两个特定单词之间的单词?

转载 作者:太空宇宙 更新时间:2023-11-04 09:44:43 25 4
gpt4 key购买 nike

用户将输入一个包含两个“bread”单词的字符串值。我的程序将打印给定字符串中第一次和最后一次出现“bread”之间的字符串,或者打印“There is no Sandwich!”如果没有两片面包。例如,对于输入“breadlolbread”,输出应为“lol”。

String a = "There is no sandwich!";

for (int i =0;i<len-3;i++) {
if ((s.charAt(i)== 'b')&&(s.charAt(i+1)== 'r')&&(s.charAt(i+2)== 'e')&&(s.charAt(i+3)== 'a')&&(s.charAt(i+4)== 'd')) {

}
}

最佳答案

你可以这样做:

  public static void main(String[] args) {
String text = "There are two bread which are very cool bread.";
String bread = "bread";
//make a new string by taking everything from first index of bread string+length of a bread string word and the last index of bread.
String inBEtween = text.substring(text.indexOf(bread)+bread.length(), text.lastIndexOf(bread));
//if the length inbetween trimmed of leading and tailing whitespace is greater than 0, print inBetween, otherwise print "No sandwich".
if (inBEtween.trim().length() > 0) {
System.out.println(inBEtween);
} else {
System.out.println("No sandwich.");
}
}

当然,您也可以使用正则表达式来做到这一点

 public static void main(String[] args) {
String text = "There are two bread bread.";
String pattern = "(?<=bread)(.*)(?=bread)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(text);
if (m.find()) {
System.out.println(m.group());
} else {
System.out.println("No sandwich");
}
}

关于java - 如何检查并显示其他两个特定单词之间的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55562211/

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