Skip to content

Instantly share code, notes, and snippets.

@lisakstep
Created February 8, 2014 17:00
Show Gist options
  • Save lisakstep/8886722 to your computer and use it in GitHub Desktop.
Save lisakstep/8886722 to your computer and use it in GitHub Desktop.
This file removes a specified character from a string of text. Stanford CS106a assignment 4.2
import acm.program.ConsoleProgram;
/** RemoveCharacters takes a string and a character, removing all
* occurences of the character from the given string
*/
/**
* @author Lisa Stephens
* Complete
* written on 2/6/2014 as a response to Stanford CS 106a exercise 4.2
* The run() method consists of test cases given by the assignment.
*
*/
public class RemoveCharacters extends ConsoleProgram{
public void run() {
println(removeAllOccurrences("This is a test", 't') );
println (removeAllOccurrences("Summer is here!", 'e') );
println(removeAllOccurrences("---0---", '-') );
}
private String removeAllOccurrences (String str1, char ch) {
while (true) {
// Find the start of the character to be removed
int index = str1.indexOf(ch);
// If there are no more occurrences, you're done
if (index == -1 ) {
return str1;
}
// If the character is found in the string, remove it
str1 = str1.substring(0, index) + str1.substring(index + 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment