Contents

How to concatenate letters to create a string (with.Java)

   Sep 1, 2023     2 min read

In this article, we learned about How to concatenate characters to create a string (with.Java)

We’re going to learn 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

Given a string my_string and an array of integers index_list as parameters, write a solution function that returns a string concatenating the letters of the indexes corresponding to the elements of index_list in my_string.

Example input and output

my_string: “cvsgiorszzzmrpaqpe” index_list: [16, 6, 5, 3, 12, 14, 11, 11, 17, 12, 7] result: “programmers”

In my_string in Example 1, the letters corresponding to indexes 3, 5, 6, 11, 12, 14, 16, and 17 are g, o, r, m, r, a, p, and e, respectively, so the letters of the indexes corresponding to the elements in index_list in my_string are p, r, o, g, r, a, m, m, m, e, r, and s, in that order. Therefore, we return “programmers”.

My solution to the problem

import java.util.*;
class Solution {
    public String solution(String my_string, int[] index_list) {
        String answer = "";
        ArrayList<Character> arr = new ArrayList<Character>();

        for(int i = 0; i < index_list.length; i++){
            arr.add(my_string.charAt(index_list[i]));
        }
        for(int j = 0; j < arr.size(); j++){
            answer += arr.get(j);
        }
        } return answer;
    }
}
Solution Explained

The problem is to sequentially extract the elements of index_list from my_string, store them, and print them. Therefore, we need to index the string. So, we create an array arr, which is an ArrayList, as a Character and get the string as an index one by one. So I use the .charAt() function to extract my_string one by one by index and save it. Then in answer, I store the arr of type character in a loop.