1 回答

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