How to concatenate substring to create a string (with.Java)
In this article, we learned how to concatenate partial strings to create a string (with.Java).
Weāve been solving coding test problems, reflecting on the problems weāve solved, and learning about other ways to solve them.
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 of concatenated substring corresponding to parts of the elements of each my_strings.
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.
I have inserted parts[i][0], parts[i][1]+1 in the arguments to the substring() function, 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.