gpt4 book ai didi

java - 返回给定字符串中第一次和最后一次出现 "bread"之间的字符串

转载 作者:行者123 更新时间:2023-11-29 07:39:32 25 4
gpt4 key购买 nike

这个问题来自 coding bat,之前可能有人问过。请查看代码。

三明治是两片面包,中间夹着一些东西。返回给定字符串中第一个和最后一个出现“bread”之间的字符串,如果没有两片面包则返回空字符串“”。

getSandwich("breadjambread") → "jam"
getSandwich("xxbreadjambreadyy") → "jam"
getSandwich("xxbreadyy") → ""

我的代码是

public static String getSandwich(String str) {
int ind = str.indexOf("bread");
int laind = str.lastIndexOf("bread");
if(!(laind == -1 ))return (str.substring(ind+5,laind)) ;
return "";
}

我得到了

Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -5 (line number:4)

对于这个输入 getSandwich("xxbreadyy")

最佳答案

看下面的代码

public static String getSandwich(String str) {
int ind = str.indexOf("bread");
int laind = str.lastIndexOf("bread");
if((laind != -1 ) && (ind!=laind))
return (str.substring(ind+5,laind)) ;
return "";
}

我将 (ind!=laind) 添加到检查第一个和最后一个“面包”是否不同的条件中。

参见 live demo 在这里。

关于java - 返回给定字符串中第一次和最后一次出现 "bread"之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31838896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com