Posted on Leave a comment

Remove all Occurrence

This is number 2 from handout #4 : string processing.

[code lang=”java”]/*
* RemoveAllOccurences
*/

import acm.program.*;

public class RemoveAllOccurences extends ConsoleProgram{
public void run(){
while(true){ // infinite loop
String str1 = readLine("Give me a string(q to exit): "); // q as a sentinel to break out of the loop
if(str1.equals("q"))
break;
String str2 = readLine("Give me a character to remove: "); // give me the char

int charIndex = 0; // get the first char only
char ch = str2.charAt(charIndex); //

println(removeAllOccurrence(str1,ch)); // call removeAllOccurence
}
}

// remove all occurrence of a char in a string
private String removeAllOccurrence(String str, char ch){
String result = ""; // declare a new String object result
int firstIndex = 0; // beginning of the string
int indexChar =str.indexOf(ch); // find the index of the first occurrence
while(indexChar!=-1){ //loop through the string str until we find all occurrence
result+=str.substring(firstIndex,indexChar); //iterate
firstIndex = indexChar+1; // skip the char
indexChar = str.indexOf(ch, firstIndex); // get the next index of the next substring
}
return result+str.substring(firstIndex); //add the end of the result string and return it
}
}[/code]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.