4

So I'm playing around string manipulation. I'm done replacing white space characters with hyphens. Now I want to combine replacing white spaces characters and removing apostrophe from string. How can I do this?

This is what I've tried so far:

    String str = "Please Don't Ask Me";
    String newStr = str.replaceAll("\\s+","-");

    System.out.println("New string is " + newStr);

Output is:

Please-Don't-Ask-Me

But I want the output to be:

Please-Dont-Ask-Me

But I can't get to work removing the apostrophe. Any ideas? Help is much appreciated. Thanks.

ADTC
  • 8,999
  • 5
  • 68
  • 93
Dunkey
  • 1,900
  • 11
  • 42
  • 72

3 Answers3

10

Try this:

String newStr = str.replaceAll("\\s+","-").replaceAll("'", "");

The first replaceAll returns the String with all spaces replaced with -, then we perform on this another replaceAll to replace all ' with nothing (Meaning, we are removing them).

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • This is OK unless you're dealing with really big strings... in that case an explicit `matcher.find() - matcher.appendReplacement()` loop would be needed. – Marko Topolnik Jan 05 '14 at 12:57
  • @MarkoTopolnik [Indeed](http://stackoverflow.com/questions/7658568/most-efficient-way-to-use-replace-multiple-words-in-a-string). – Maroun Jan 05 '14 at 12:57
  • @MarkoTopolnik can you give me some implementations of matcher.find()? I find the tutorials very confusing for a beginner – Dunkey Jan 05 '14 at 13:03
  • 1
    Have you clicked through Maroun's "Indeed" hyperlink above? I believe that answer covers it. – Marko Topolnik Jan 05 '14 at 13:04
1

It's very easy, use replaceAll again on the resulted String:

String newStr = str.replaceAll("\\s+","-").replaceAll("'","");
Maroun
  • 94,125
  • 30
  • 188
  • 241
Shashank
  • 712
  • 15
  • 33
1

Try this..

String s = "This is a string that contain's a few incorrect apostrophe's. don't fail me now.'O stranger o'f t'h'e f'u't'u'r'e!";
        System.out.println(s);

        s = s.replace("\'", "");

        System.out.println("\n"+s);