removing consecutive duplicate characters

Q

qazmlp1209

Is there a simple/direct way of removing the consecutive duplicate
characters in a String?
Assume I have a string like this:
abc**de**fg

It should be changed as:
abc*de*fg
 
A

Andrey Kuznetsov

Is there a simple/direct way of removing the consecutive duplicate
characters in a String?
Assume I have a string like this:
abc**de**fg

It should be changed as:
abc*de*fg

something like this:

String removeCDChars(String s) {
StringBuffer sb = new StringBuffer();
//add first char
char lastChar = s.charAt(0);
sb.append(lastChar);

int len = sb.size();

for(int i = 1; i < len; i++) {
char c = s.charAt(i);
if(c != lastChar) {
sb.append(c);
lastChar = c;
}
}

return sb.toString();
}
 
O

Oliver Wong

Andrey Kuznetsov said:
something like this:

String removeCDChars(String s) {
StringBuffer sb = new StringBuffer();
//add first char
char lastChar = s.charAt(0);
sb.append(lastChar);

int len = sb.size();

for(int i = 1; i < len; i++) {
char c = s.charAt(i);
if(c != lastChar) {
sb.append(c);
lastChar = c;
}
}

return sb.toString();
}

The method will fail on the empty string. It also might not handle
unicode strings with characters outside the basic multilingual plane too
well. But otherwise, this is essentially the algorithm I'd recommend as
well.

- Oliver
 
Q

qazmlp1209

String removeCDChars(String s) {
StringBuffer sb = new StringBuffer();
//add first char
char lastChar = s.charAt(0);
sb.append(lastChar);

int len = sb.size();
int len = s.length();
After the above change, the code works perfectly fine(with the
exception to what Oliver has quoted).
 
A

Andrey Kuznetsov

int len = s.length();
right, conclusion - don't try to programm in outlook ;-)
After the above change, the code works perfectly fine(with the
exception to what Oliver has quoted).
hmm, yes, I should add check for empty String.

Andrey
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top