1

I am attempting to write code to remove a whole sentence from a paragraph. It doesn't matter which sentence it is, but it needs to be at least one.

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

This is the code I currently have. It is currently printing the exact same string that I begin with. Any one have any ideas?

EDIT: I was wrong to imply that any sentence should be removed. I meant any sentence aside from the first. Preferably the sentence to be removed would fall somewhere within the middle of the string, and the actual application would be used in very large strings.

hippietrail
  • 15,848
  • 18
  • 99
  • 158
  • 1
    How about just deleting every character until you reach a `.` – takendarkk Sep 16 '14 at 23:08
  • debug it by look at the values to see whats happening, print out sentancestart and sentanceend to see if they are different. looks like they are evaluating to the same values. – Dave Sep 16 '14 at 23:08

3 Answers3

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.

Rahul
  • 76,197
  • 13
  • 71
  • 125
1

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

I thought I had tried that, but apparently not

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.
nostromo
  • 1,435
  • 2
  • 17
  • 23
  • I tried that, but somehow it destroyed the formatting of the final product. I must not be doing it right, hehe – user2651000 Sep 16 '14 at 23:14
  • You may have run into a problem with split("."). Period is a regex character and split accepts regexes -- so escape the period with \\. – nostromo Sep 16 '14 at 23:17