For outputting n characters after a string (with.Java)
In this article, we looked at printing n characters after a string (with.Java).
We’re going to learn as we go along by solving coding test problems, looking back at the problems we solved, and exploring other ways to solve them.
Let’s start with the problem.
Problem
Given a string my_string and an integer n as parameters, write a solution function that returns a string of n characters after my_string.
Example input and output
my_string: “ProgrammerS123”
n: 11
result: “grammerS123”
The last 11 characters in my_string are “grammerS123”, so we return this string.
My solution to the problem
class Solution {
public String solution(String my_string, int n) {
String answer = "";
answer = my_string.substring(my_string.length() - n);
return answer;
}
}
Explanation of the solution
Since my_string is supplied as a string, we thought we could just truncate the trailing elements with substring and output them in the answer variable as my_string.substring(my_string.length() - n); for a total length of n, and output the trailing elements by index.
This is possible because substring() returns a value for truncation.
The reason we subtracted n from the full length is because if we just did substring(n), it would truncate the string from the 11th index of my_string when n is 11 because of the nature of substring, and we would get 123.
So if you do the opposite and insert the entire length of my_string minus n into the substring, you’ll be left with just that value, and the trailing string will be truncated by the substring and returned.
In this case, we’ve implemented it so that the n characters after the string are output.