替换 Java 字符串中的破折号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17761717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 14:54:25  来源:igfitidea点击:

Replace dash character in Java String

javastringreplacestr-replace

提问by wawanopoulos

I tried to replace "-" character in a Java String but is doesn't work :

我试图替换 Java 字符串中的“-”字符,但不起作用:

str.replace("\u2014", "");

Could you help me ?

你可以帮帮我吗 ?

回答by Suresh Atta

String is Immutable in Java. You have to reassign it to get the result back:

字符串在 Java 中是不可变的。您必须重新分配它才能返回结果:

String str ="your string with dashesh";
str= str.replace("\u2014", "");

See the APIfor details.

有关详细信息,请参阅API

回答by prime

this simply works..

这只是有效..

    String str = "String-with-dash-";
    str=str.replace("-", "");
    System.out.println(str);

output - Stringwithdash

输出 - 带破折号的字符串

回答by Lefteris Bab

It's quite easy. You can use an Apache library, that will be useful while you develop an application. This is apache-commons-lang. You can do the following:

这很容易。您可以使用 Apache 库,这在您开发应用程序时会很有用。这是 apache-commons-lang。您可以执行以下操作:

public class Main {

    public static void main(String[] args) {

        String test = "Dash - string";
        String withoutDash = StringUtils.replace(test, "-", "");
        System.out.println(withoutDash);
    }

}