簡體   English   中英

如何檢查和顯示其他兩個特定單詞之間的單詞?

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

用戶將輸入一個包含兩個“面包”字的字符串值。 我的程序將打印出給定字符串中“面包”的第一個和最后一個外觀之間的字符串,或者如果沒有兩塊面包,則打印“沒有三明治!”。 例如,對於輸入“ 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')) {

    }   
}

您可以通過兩種方法來完成此操作。 第一個是創建一個正則表達式,該表達式將匹配整個句子,即用戶提供的兩個單詞,其中兩個單詞之間。

另一種方法可能更簡單,您可以使用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]);
    }
}

您可以執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM