1

用户将输入一个包含两个“面包”字的字符串值。我的程序将打印出给定字符串中第一次和最后一次出现“面包”之间的字符串,或者打印“没有三明治!” 如果没有两片面包。例如,对于输入“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')) {

    }   
}
4

2 回答 2

0

您可以通过两种不同的方式执行此操作。第一个是创建一个正则表达式来匹配整个句子,即用户提供的两个单词与它们之间的单词。

另一种方法可能更简单,您可以使用split()方法将字符串拆分为单独的单词,然后简单地遍历整个数组以找到您要查找的单词。这个例子是:

String userWord = "bread";
String word = "There are bread various bread breeds of dogs";
String[] wordSplit = word.split("");
for(int i = 0; i < wordSplit.length-2; i++) {
    if(wordSplit[i].equals(userWord) && wordSplit[i+2].equals(userWord)) {
        System.out.println(wordSplit[i+1]);
    }
}
于 2019-04-07T18:36:27.517 回答
0

您可以执行以下操作:

  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");
        }
  }
于 2019-04-07T18:47:52.713 回答