在Java中删除字符串的一部分

94
我想从一个字符中删除字符串的一部分,即:
源字符串:
manchester united (with nice players)

目标字符串:
manchester united

5
你如何知道哪些部分需要保留,哪些需要舍弃?如果不知道这一点,就无法回答你的问题。 - Raedwald
12个回答

1
// 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
你可以使用replace来修复你的字符串。下面的代码将返回左括号前的所有内容,并删除所有前导和尾随的空白。如果字符串以左括号开头,则会将其保留不变。
str = "manchester united (with nice players)"
matched = str.match(/.*(?=\()/)
str.replace(matched[0].strip) if matched

这似乎在Java中无法工作。它可能是ECMAscript的派生物。你有什么方法可以让这段代码在Java中正常工作吗? - 1111161171159459134

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接