Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove part of string after or before a specific word in java

Tags:

java

Is there a command in java to remove the rest of the string after or before a certain word;

Example:

Remove substring before the word "taken"

before: "I need this words removed taken please"

after:

"taken please"

like image 592
user3286012 Avatar asked Mar 20 '15 20:03

user3286012


People also ask

How do you cut a string after a specific word in Java?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How do I remove a string after a specific character in Java?

The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove.

How do you cut a string before a specific character in Java?

trim() . trim() removes spaces before the first character (which isn't a whitespace, such as letters, numbers etc.) of a string (leading spaces) and also removes spaces after the last character (trailing spaces).


1 Answers

String are immutable, you can however find the word and create a substring:

public static String removeTillWord(String input, String word) {
    return input.substring(input.indexOf(word));
}

removeTillWord("I need this words removed taken please", "taken");
like image 159
Crazyjavahacking Avatar answered Nov 05 '22 12:11

Crazyjavahacking