5

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

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

Could you help me ?

wawanopoulos
  • 9,614
  • 31
  • 111
  • 166

3 Answers3

11

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

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

See the API for details.

Maroun
  • 94,125
  • 30
  • 188
  • 241
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
5

this simply works..

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

output - Stringwithdash

prime
  • 14,464
  • 14
  • 99
  • 131
0

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:

public class Main {

    public static void main(String[] args) {

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

}
Lefteris Bab
  • 787
  • 9
  • 19
  • 1
    the apache commons lang library is a bit overkill to replace a dash in a string, java manages fine on its own – flup Jul 20 '13 at 12:04
  • Yes, but did you see my comment ? "that will be useful while you develop an application" That's why I proposed this solution – Lefteris Bab Jul 20 '13 at 12:21