Dunkey
Dunkey

Reputation: 1922

Remove apostrophe and white space from string

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.

Upvotes: 4

Views: 16160

Answers (3)

user6224849
user6224849

Reputation:

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);

Upvotes: 1

Shashank
Shashank

Reputation: 782

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

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

Upvotes: 1

Maroun
Maroun

Reputation: 95978

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).

Upvotes: 10

Related Questions