亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何檢查特定字符串是否在另一個字符串中多次出現?

如何檢查特定字符串是否在另一個字符串中多次出現?

皈依舞 2022-10-07 17:04:20
我的代碼從用戶那里獲取輸入,如果有兩個"bread"子字符串,則打印它們之間的字符串。例如,"breadjavabread"輸出"java"。但是,當我的代碼只有一個"bread"字符串時,會彈出一個錯誤。例如,"usjdbbreaddudub"。我該如何解決這個問題?String cheese = "no bread";String bread = "bread";for (int i = 0; i < s.length() - 5; i++){  String m = s.substring(i, i + 5);  if (m.equals(bread))  {    cheese = s.substring(s.indexOf(bread) + bread.length(), s.lastIndexOf(bread));  }}System.out.print(cheese);
查看完整描述

1 回答

?
慕哥9229398

TA貢獻1877條經驗 獲得超6個贊

有很多方法可以解決這個問題。這是其中的3個


比較indexOf和lastIndexOf


String cheese;

String bread = "bread";

int firstIndex = s.indexOf(bread);

int lastIndex = s.lastIndexOf(bread);

if (firstIndex == -1) {

    cheese = "no bread";

} else if (lastIndex == firstIndex) {

    cheese = "only one bread";

}

cheese = s.substring(firstIndex + bread.length(), lastIndex);


System.out.print(cheese);

常用表達:


Matcher m = Pattern.compile("bread(.+?)bread").matcher(s);

if (m.find()) {

    System.out.println(m.group(1));

} else {

    System.out.println("Not enough bread");

}

分裂:


String[] parts = s.split("bread");

if (parts.length == 3) {

    System.out.println(parts[1]);

} else {

    System.out.println("Not enough or too much bread");

}



查看完整回答
反對 回復 2022-10-07
  • 1 回答
  • 0 關注
  • 82 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號