Contents

Capitalize specific characters (with.Java)

   Oct 12, 2023     2 min read

In this article, we learned how to capitalize certain characters.

We’ll do this by solving a coding test problem, reflecting on the problem we solved, and learning about other ways to solve it.

Let’s start with the problem

Problem

Given a string my_string of lowercase letters and a string alp of one lowercase letter as parameters, write a solution function that returns a string that capitalizes all the letters in my_string that correspond to alp.

Example input and output
myStringalpresult
“programmers”“p”“Programmers”

My solution to the problem

class Solution {
    public String solution(String my_string, String alp) {
        StringBuilder answer = new StringBuilder();
        for(int i = 0; i < my_string.length(); i++){
            char currentChar = my_string.charAt(i);
            if(currentChar == alp.charAt(0)){
                answer.append(Character.toUpperCase(currentChar));
            } else{
                answer.append(currentChar);
            }
        }
        } return answer.toString();
    }
}
solution description

public String solution(String my_string, String alp): A function that takes two string parameters my_string and alp as input and processes the string.

StringBuilder answer = new StringBuilder();: Creates a StringBuilder object to hold the resulting string. We will use this object to construct the string.

for(int i = 0; i < my_string.length(); i++) { … }: Execute a loop for each character in the given string my_string.

char currentChar = my_string.charAt(i);: Store the character of the string currently being processed by the iterator in the currentChar variable.

if(currentChar == alp.charAt(0)) { … } else { … }: Compare if the current character is equal to the given character alp.

answer.append(Character.toUpperCase(currentChar));: If the current character is equal to the given character alp, convert it to upper case and add it to the result string answer.

answer.append(currentChar);: If the current character is different from the given character alp, keep it as is and add it to the result string answer.

return answer.toString();: Finally, return the string stored in answer as a string.