Remove part of string in Java

后端 未结 12 1764
遥遥无期
遥遥无期 2020-11-28 04:22

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

Source string:

manchester united (with nice players)

Target string:

12条回答
  •  情书的邮戳
    2020-11-28 04:52

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

提交回复
热议问题