Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove part of string in Java

Tags:

java

string

I want to remove a part of string from one character, that is:

Source string:

manchester united (with nice players) 

Target string:

manchester united 
like image 362
zmki Avatar asked Jan 01 '12 19:01

zmki


People also ask

How do you remove part of a string in Java?

Java Remove substring from String Notice that replaceAll and replaceFirst methods first argument is a regular expression, we can use it to remove a pattern from string. Below code snippet will remove all small case letters from the string.

How do I remove part of a string?

You can also remove a specified character or substring from a string by calling the String. Replace(String, String) method and specifying an empty string (String. Empty) as the replacement. The following example removes all commas from a string.


1 Answers

There are multiple ways to do it. If you have the string which you want to replace you can use the replace or replaceAll methods of the String class. If you are looking to replace a substring you can get the substring using the substring API.

For example

String str = "manchester united (with nice players)"; System.out.println(str.replace("(with nice players)", "")); int index = str.indexOf("("); System.out.println(str.substring(0, index)); 

To replace content within "()" you can use:

int startIndex = str.indexOf("("); int endIndex = str.indexOf(")"); String replacement = "I AM JUST A REPLACEMENT"; String toBeReplaced = str.substring(startIndex + 1, endIndex); System.out.println(str.replace(toBeReplaced, replacement)); 
like image 92
mprabhat Avatar answered Sep 26 '22 06:09

mprabhat