为了账号安全,请及时绑定邮箱和手机立即绑定

如何检查特定字符串是否在另一个字符串中多次出现?

如何检查特定字符串是否在另一个字符串中多次出现?

皈依舞 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 关注
  • 88 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号