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"
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"