Removing one character

Question: Write a method that will remove any given character from a string.

Related Tags:

Questions

  • Are we given the position or the letter?
  • If the latter case, is it the first occurrence?

Algorithm

Let's make two functions. One that takes in the position, and the other that takes in the letter. This is known as operator overloading. We'll assume that it's just the first occurrence of the letter we're trying to remove.

First search through the String until the specified character is found. We then call our other method (which accepts the int position) to remove the element.

Algorithm Implementation in Java

public class RemoveCharacter {
	public static void main(String[] args) {

		System.out.println(removeChar("Hello", 3));
		System.out.println(removeChar("Hello", 'l'));

	}

	static String removeChar(String input, char c) {

		for (int i = 0; i < input.length(); i++) {
			if (input.charAt(i) == c) {
				return removeChar(input, i);
			}
		}

		return null;

	}

	static String removeChar(String input, int pos) {

		if (pos >= input.length() || pos < 0) return null;

		return input.substring(0, pos) + input.substring(pos + 1);

	}
}

Came up with a better solution or have a question? Comment below!