简体   繁体   中英

How can I check and display the word between two other specific words?

The user will enter a string value that will contain two “bread” word. My program will printout the string that is between the first and last appearance of "bread" in the given string, or print “There is no sandwich!” if there are not two pieces of bread. For example, for the input "breadlolbread", the output should be "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')) {

    }   
}

You can do this in two various ways. First one is to create a regular expression that will match the whole sentence ie two words provided by the user with the word between them.

The other way is probably easier, You can use split() method to split String into the separate words and then simply iterate over the whole array to find the words you are looking for. The example would be :

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

You could do something like:

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

Of course, you could do this with regex too

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM