Contents

String Case Conversion in Arrays (with.Java)

   Nov 4, 2023     1 min read

In this article, we learned how to convert a string case in an array.

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

Let’s start with the problem

Problem

You are given an array of strings, strArr.

Complete the solution function that returns the string at the odd-numbered index in the array with all characters uppercase and the string at the even-numbered index with all characters lowercase, given that all elements are alphabetic.

Example input and output
strArrresult
[“AAA”,”BBB”,”CCC”,”DDD”][“aaa”,”BBB”,”ccc”,”DDD”]
[“aBc”,”AbC”][“abc”,”ABC”]

My solution to the problem

class Solution {
    public String[] solution(String[] strArr) {
        String[] answer = new String[strArr.length];
        for(int i = 0; i < strArr.length; i++){
            if(i % 2 == 0){
                answer[i] = strArr[i].toLowerCase();
            } else{
                answer[i] = strArr[i].toUpperCase();
            }
        }
        } return answer;
    }
}
solution description

String[] answer = new String[strArr.length];: Create a string array answer to store the result. Create it with the same length as the input array.

for(int i = 0; i < strArr.length; i++) : Iterate over the input array strArr, examining each string.

if(i % 2 == 0) : If the current index i is an even number:

Convert the current string to lowercase and store it in the answer array.

else : If the current index i is odd:

Convert the current string to uppercase and store it in the ANSWER array.

return answer;: Returns the answer array with the conversion done for all strings.

This code creates and returns a new array with the strings at even indices in the input array converted to lowercase and the strings at odd indices converted to uppercase.