Java删除一切东西

时间:2013-02-18 17:57:34

标签: java

以下是一些代码:

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

这有效,但是有一个问题:对于某些蛋糕值(例如网站的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)

3 个答案:

答案 0 :(得分:2)

为此我会想到正则表达式。

这篇文章举了一个在Java中使用正则表达式的例子:Java regex to remove all trailing 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);
}

答案 1 :(得分: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);

答案 2 :(得分:0)

你可以试试这个:

String ice = "ice";
String sandwiches = "sandwiches";
cakes = cakes.substring(cakes.indexOf(ice),cakes.indexOf(sandwiches)+sandwiches.length());