Tailor
Tailor

Reputation: 303

Java replace multiple characters in a String with one character

Is it possible to replace multiple characters in a string with one? I saw some ways to do this with loops, but isnt it possible to do it easier?

For example:

input: /////Hello//this////////is///Java

output: /Hello/this/is/Java

Upvotes: 2

Views: 531

Answers (2)

Lahcen YAMOUN
Lahcen YAMOUN

Reputation: 691

This is a complete answer:

String Str = new String("Your string");
Set<Character> charsOfString = new HashSet<Character>();
int len = Str.length();
for(int i = 0 ; i < len ; i++)
    charsOfString.add(Str.charAt(i));
for (Character c : charsOfString) 
    Str = Str.replaceAll(c + "+", c + "");

This will delete all duplicated characters of your string

Upvotes: 0

Michal Lonski
Michal Lonski

Reputation: 887

Something like this:

String s = "/////Hello//this////////is///Java";
System.out.println(s.replaceAll("/+", "/"));

Upvotes: 2

Related Questions