187k views
1 vote
Write a method named removeDuplicates that accepts a string parameter and returns a new string with all consecutive occurrences of the same character in the string replaced by a single occurrence of that character. For example, the call of removeDuplicates("bookkeeeeeper") should return "bokeper" .

2 Answers

1 vote

Final answer:

To remove consecutive occurrences of the same character in a string, you can iterate through the string and compare each character with the previous one. If they are the same, skip that character, otherwise, add it to a new string.

Step-by-step explanation:

To remove consecutive occurrences of the same character in a string, you can iterate through the string and compare each character with the previous one. If they are the same, skip that character, otherwise, add it to a new string. Here's an example implementation:


public static String removeDuplicates(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char currentChar = str.charAt(i);
if (i == 0 || currentChar != str.charAt(i - 1)) {
result.append(currentChar);
}
}
return result.toString();
}


When you call the removeDuplicates method with the string bookkeeeeeper, it will return bokeper, as all consecutive occurrences of the same character have been replaced by a single occurrence.

User Khalid Dabjan
by
5.5k points
6 votes

Answer:

//Method definition

//Method receives a String argument and returns a String value

public static String removeDuplicates(String str){

//Create a new string to hold the unique characters

String newString = "";

//Create a loop to cycle through each of the characters in the

//original string.

for(int i=0; i<str.length(); i++){

// For each of the cycles, using the indexOf() method,

// check if the character at that position

// already exists in the new string.

if(newString.indexOf(str.charAt(i)) == -1){

//if it does not exist, add it to the new string

newString += str.charAt(i);

} //End of if statement

} //End of for statement

return newString; // return the new string

} //End of method definition

Sample Output:

removeDuplicates("bookkeeeeeper") => "bokeper"

Step-by-step explanation:

The above code has been written in Java. It contains comments explaining every line of the code. Please go through the comments.

The actual lines of codes are written in bold-face to distinguish them from comments. The program has been re-written without comments as follows:

public static String removeDuplicates(String str){

String newString = "";

for(int i=0; i<str.length(); i++){

if(newString.indexOf(str.charAt(i)) == -1){

newString += str.charAt(i);

}

}

return newString;

}

From the sample output, when tested in a main application, a call to removeDuplicates("bookkeeeeeper") would return "bokeper"

User Codingbbq
by
6.7k points