Ads by ProfitSence

Remove part of string in Java

Last Updated on Wednesday 5th Oct 2022

Remove Part of String

  • 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.

Definition and Usage

  • The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.


					public String replace(char searchChar, char newChar)



  • searchChar - A char, representing the character that will be replaced by the new character
  • newChar - A char, representing the character to replace the searchChar with

Remove Part of String Java

					public class Main {
  public static void main(String[] args) {
    String str = "Hello Peoples (from Earth)";
    System.out.println(str.replace("(from Earth)", ""));
    int index = str.indexOf("(");
    System.out.println(str.substring(0, index));

					// Hello Peoples
// Hello Peoples


How to Remove part of a String in Java

					public class RemoveSubString {

  public static void main(String[] args) {
    String nums = "1,2,3,4,5";
    String removeMe = "3,";

    String newOne = nums.replace(removeMe, "");


					// 1,2,3,4,5
// 1,2,4,5