0

这是一些代码:

    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)
4

3 回答 3

2

为此,我想到了正则表达式。

这篇文章有一个在 Java 中仅使用正则表达式的示例:Java regex to remove all tr​​ailing numbers?

在这种情况下,表达式将类似于:"ice.*sandwiches"

编辑:我以为我们要删除这些词。我的错。这是一些应该做更多你正在寻找的代码。

Pattern p = Pattern.compile("ice.*sandwiches");
Matcher m = p.matcher("I like to eat ice cream sandwiches at night");
while (m.find()) {
    String s = m.group(1);
}
于 2013-02-18T18:00:00.340 回答
0

您可以使用正则表达式或仅使用 String.indexOf() 等。

String wordOne = "ice";
String wordTwo = "sandwiches";

startIndex = cakes.indexOf(wordOne);
endIndex = cakes.indexOf(wordTwo) + wordTwo.length();

String result = cakes.substring(startIndex, endIndex);
于 2013-02-18T18:03:26.877 回答
0

你可以试试这个:

String ice = "ice";
String sandwiches = "sandwiches";
cakes = cakes.substring(cakes.indexOf(ice),cakes.indexOf(sandwiches)+sandwiches.length());
于 2013-02-18T18:06:21.817 回答