user3796292
user3796292

Reputation: 141

Remove a substring from a string starting from a character

Narrator: Kids, if you are single is all this happy ever after. [Title: the year of 2030]. But only one of your stories can end that way. The rest end with someone getting hurt. This is one of those stories, and it starts… with a shirt.

From the string above, how will I remove the sentence surrounded by []. Thus, this

[Title: the year of 2030].

will be taken out. The string then becomes

Narrator: Kids, when you’re single all you’re looking for is happily ever after. But only one of your stories can end that way. The rest end with someone getting hurt. This is one of those stories, and it starts… with a shirt.

Upvotes: 2

Views: 1811

Answers (3)

Sam
Sam

Reputation: 513

Or you can try this.

String str = "Narrator: Kids,if you are single is all this happy ever after. [Title: the year of 2030]. But (...)";
    StringBuilder strBuild = new StringBuilder(str);

      int start = str.indexOf("[");
      int end = str.indexOf("]")+1;
    strBuild.delete(start, end);
    System.out.println(strBuild);

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

Try this :

public static void main(String[] args) {
    String s = "Narrator: Kids, if you are single is all this happy ever after. [Title: the year of 2030]. But only one of your stories can end that way. The rest end with someone getting hurt. This is one of those stories, and it starts… with a shirt.";
    System.out.println(s.replaceAll("\\[.*?\\]", ""));
}

O/P :

Narrator: Kids, if you are single is all this happy ever after. . But only one of your stories can end that way. The rest end with someone getting hurt. This is one of those stories, and it starts… with a shirt.

Upvotes: 4

Elliott Frisch
Elliott Frisch

Reputation: 201517

You could use a regular expression with String.replaceAll(String, String), but you need to escape the [ and ] characters (because they have special meaning in a regex). Something like,

String story = "Narrator: Kids, if you are single is all this happy "
    + "ever after. [Title: the year of 2030]. But only one of your stories "
    + "can end that way. The rest end with someone getting hurt. "
    + "This is one of those stories, and it starts… with a shirt.";
story = story.replaceAll("\\[.*\\]", "");
System.out.println(story);

Upvotes: 1

Related Questions