Remove part of string in Java

后端 未结 12 1677
遥遥无期
遥遥无期 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:59

    String Replace

    String s = "manchester united (with nice players)";
    s = s.replace(" (with nice players)", "");
    

    Edit:

    By Index

    s = s.substring(0, s.indexOf("(") - 1);
    
    0 讨论(0)
  • 2020-11-28 05:03

    I would at first split the original string into an array of String with a token " (" and the String at position 0 of the output array is what you would like to have.

    String[] output = originalString.split(" (");
    
    String result = output[0];
    
    0 讨论(0)
  • 2020-11-28 05:06
    originalString.replaceFirst("[(].*?[)]", "");
    

    https://ideone.com/jsZhSC
    replaceFirst() can be replaced by replaceAll()

    0 讨论(0)
  • 2020-11-28 05:06

    You could use replace to fix your string. The following will return everything before a "(" and also strip all leading and trailing whitespace. If the string starts with a "(" it will just leave it as is.

    str = "manchester united (with nice players)"
    matched = str.match(/.*(?=\()/)
    str.replace(matched[0].strip) if matched
    
    0 讨论(0)
  • 2020-11-28 05:10
    // Java program to remove a substring from a string
    public class RemoveSubString {
    
        public static void main(String[] args) {
            String master = "1,2,3,4,5";
            String to_remove="3,";
    
            String new_string = master.replace(to_remove, "");
            // the above line replaces the t_remove string with blank string in master
    
            System.out.println(master);
            System.out.println(new_string);
    
        }
    }
    
    0 讨论(0)
  • 2020-11-28 05:10

    If you just need to remove everything after the "(", try this. Does nothing if no parentheses.

    StringUtils.substringBefore(str, "(");
    

    If there may be content after the end parentheses, try this.

    String toRemove = StringUtils.substringBetween(str, "(", ")");
    String result = StringUtils.remove(str, "(" + toRemove + ")"); 
    

    To remove end spaces, use str.trim()

    Apache StringUtils functions are null-, empty-, and no match- safe

    0 讨论(0)
提交回复
热议问题