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

时间:2019-04-07 18:15:23

标签: java string for-loop

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

    }   
}

2 个答案:

答案 0 :(得分:0)

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

另一种方法可能更容易,您可以使用split()方法将String拆分为单独的单词,然后简单地遍历整个数组以查找所需的单词。示例为:

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

答案 1 :(得分: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");
        }
  }