1 回答

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");
}
添加回答
舉報(bào)