Contents

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

   Sep 7, 2023     1 min read

In this article, we have learned how to create a string by concatenating partial strings (with.Java).

We’re going to solve a coding test problem, reflect on the problem we solved, and learn about other ways to solve it.

Let’s start with the problem.

Problem

You are given an array of strings of equal length my_strings and a two-dimensional integer array parts as parameters.

parts[i] is of the form [s, e], meaning the substring from index s to index e of my_string[i].

Write a solution function that returns a string concatenating the substring corresponding to parts of the elements of each of my_strings in order.

Example input and output

my_string: [“progressive”, “hamburger”, “hammer”, “ahocorasick”]

queries: [[0, 4], [1, 2], [3, 5], [7, 7]]

result: “programmers”

Solving the example, the string of each substring concatenated in order is “programmers”, so it returns “programmers”.

My solution to the problem

class Solution {
    public String solution(String[] my_strings, int[][] parts) {
        String answer = "";
        for(int i = 0; i < parts.length; i++){
            answer += my_strings[i].substring(parts[i][0], parts[i][1]+1);
        }
        } return answer;
    }
}
Solution

To implement the logic, we create a loop that traverses the length of parts, and then store the string elements of my_strings in answer of type String using the substring function.

In the argument to the substring() function, I have inserted parts[i][0], parts[i][1]+1, which means that substring will return a string starting at startIndex and ending just before endIndex.

This is because, in simple math, startIndex <= sequence number < endIndex.

To get the return value up to index, which is what the problem requires, we need to add +1 to make it <=, so we did.