第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何檢查特定字符串是否在另一個(gè)字符串中多次出現(xiàn)?

如何檢查特定字符串是否在另一個(gè)字符串中多次出現(xiàn)?

皈依舞 2022-10-07 17:04:20
我的代碼從用戶那里獲取輸入,如果有兩個(gè)"bread"子字符串,則打印它們之間的字符串。例如,"breadjavabread"輸出"java"。但是,當(dāng)我的代碼只有一個(gè)"bread"字符串時(shí),會(huì)彈出一個(gè)錯(cuò)誤。例如,"usjdbbreaddudub"。我該如何解決這個(gè)問題?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貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超6個(gè)贊

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


比較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);

常用表達(dá):


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

}



查看完整回答
反對(duì) 回復(fù) 2022-10-07
  • 1 回答
  • 0 關(guān)注
  • 81 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)