2

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

0

2 Answers 2

2

Something like this:

String s = "/////Hello//this////////is///Java";
System.out.println(s.replaceAll("/+", "/"));
Sign up to request clarification or add additional context in comments.

3 Comments

If i want to use the: String sepchar = java.io.File.separator; as the replacement it will give me the error: character to be escaped is missing. Do you have an idea why?
On my Linux "/////Hello//this////////is///Java".replaceAll("/+", java.io.File.separator) works fine. However this separator is taken from FileSystem implementation that may be different on your system. What character it gives you? And what did you try?
Ok, you probably use windows and get "\\" as separator character, quickfix is: java.io.File.separator.replace("\\", "\\\\") to be used as replacement.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.