Contents

Removing Specific Characters (with.Java)

   Dec 29, 2023     2 min read

This is the “Remove specific characters” problem.

We’re going to take a look at solving a coding test problem, provide a retrospective on how we solved it, and explore other ways to solve it.

Let’s start with the problem

Problem

Given a string my_string and a character letter as parameters, complete the solution function so that it returns a string with letter removed from my_string.

Limitations

1 ≀ length of my_string ≀ 100

letter is an alphabetic character of length 1

my_string and letter are in alphabetical case.

Distinguish between uppercase and lowercase letters.

Example input and output

my_stringletterresult
“abcdef”“f”“abcde”
“CBdbe”“B”“Cdbe”

My solution to the ### problem

class Solution {
    public String solution(String my_string, String letter) {
        StringBuilder result = new StringBuilder();
        for(char ch : my_string.toCharArray()){
            if(ch != letter.charAt(0)){
                result.append(ch);
            }
        }
    } return result.toString();
}

Solution

This code is a function that creates a new string of characters from the string my_string, excluding the specific character letter. Below is a brief explanation of the main parts of the code.

Short description of the main code

class Solution {
    public String solution(String my_string, String letter) {
        // Create a StringBuilder object to accumulate the resulting string
        StringBuilder result = new StringBuilder();

        // Convert the string my_string to an array of characters and iterate over each character
        for (char ch : my_string.toCharArray()) {
            // only add to the result if the current character is not equal to the character letter to exclude
            if (ch != letter.charAt(0)) {
                result.append(ch);
            }
        }

        // convert the final result to a string and return it
        return result.toString();
    }
}

Key steps in that code:

Create a StringBuilder object result to accumulate the final result string.

Convert the string my_string to an array of characters and iterate over each character.

Only add the character to result if the current character is not equal to the character letter to exclude.

Finally, convert result to a string and return it.

For example, calling solution(“hello”, “l”) returns “heo”.