这是一些代码:
String cakes = "I like to eat ice cream sandwiches at night";
cakes = cakes.replace("ice cream", "");
System.out.println(cakes);
这将删除冰淇淋。凉爽的。但我想要的是:
String cakes = "I like to eat ice cream sandwiches at night";
cakes = "ice" thru "sandwiches";
System.out.println(cakes);
组合操作要做的是删除除冰和三明治之间的字母之外的所有内容,使串蛋糕成为“冰淇淋三明治”。这有可能吗?
编辑:我有一个新代码:
String cakes = "I like to eat ice cream sandwiches at night";
String ice = "ice";
String sandwiches = "sandwiches";
cakes = cakes.substring(cakes.indexOf(ice),cakes.indexOf(sandwiches)+sandwiches.length());
System.out.println(cakes);
这可行,但有一个问题:对于 cake 的某些值(例如网站的 html 代码),我收到一个错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -number
at java.lang.String.substring(Unknown Source)
at package.cclass.main(cat.java:31)