1

我正在尝试编写代码以从段落中删除整个句子。它是哪一个句子并不重要,但它必须至少是一个。

    String edit = "The cow goes moo. The cow goes boo. The cow goes roo. The cow goes jew.";
    int sentencestart = (edit.substring(edit.length()/2).indexOf('.') + edit.length()/2);
    int sentenceend = edit.substring(sentencestart).indexOf('.') + sentencestart;
    edit = edit.substring(0, sentencestart) + edit.substring(sentenceend);
    System.out.println(edit);

这是我目前拥有的代码。它目前正在打印与我开始时完全相同的字符串。有人有想法么?

编辑:我错误地暗示应该删除任何句子。我的意思是除了第一句话之外的任何句子。最好将要删除的句子落在字符串中间的某个位置,并且实际应用程序将用于非常大的字符串。

4

3 回答 3

1

Why not just split by . and get the required line like

string edit = "The cow goes moo. The cow goes boo. The cow goes roo. The cow goes jew.";
return edit.Substring(edit.Split('.')[0].Length + 1,edit.Length - edit.Split('.')[0].Length - 1);

Output: The cow goes boo. The cow goes roo. The cow goes jew.

Disclaimer: Above code is in C# syntax and not Java but hopefully same can done in Java with minimal modification.

于 2014-09-16T23:11:08.547 回答
1

Just needed chance sentenceend to int sentenceend = edit.substring(sentencestart+1).indexOf('.') + sentencestart;

I thought I had tried that, but apparently not

于 2014-09-16T23:12:03.773 回答
1

Split the input by the '.' character. Then loop through the fragments, adding them all back in, but skip the 2nd sentence.

Something like this:

  public static void main(String args[]) {
    String paragraph = "Hello. This is a paragraph. Foo bar. Bar foo.";
    String result = "";
    int i = 0;
    for (String s : paragraph.split("\\.")) {
      if (i++ == 1) continue;
      result += s+".";
    }
    System.out.println(result);
  }

Results in:

Hello. Foo bar. Bar foo.
于 2014-09-16T23:12:53.530 回答