String
rightA string
contains important characters on its end (the right side). With a custom method, we can easily extract these characters.
Substring
is often useful, but it can be hard to use. It requires a begin index and an optional end index. To implement right, we calculate the begin index.
Consider a string
like "website." When we take the right 4 chars, we are left with the string
"site." Our method uses Substring
to achieve this goal.
Right(4) Input = "website" Output = "site"
Right()
calls substring in its implementation. It computes the beginning by subtracting the argument (the count of chars) from the string
length.
string
, and return it as a new string
.right()
returns the last four chars of a string
. With 7, it returns the last seven chars.public class Program { public static String right(String value, int length) { // To get right characters from a string, change the begin index. return value.substring(value.length() - length); } public static void main(String[] args) { // Test the right method. String value = "website"; String result = right(value, 4); System.out.println(result); value = "Java Virtual Machine"; result = right(value, 7); System.out.println(result); } }site Machine
A Java program can use substring directly whenever it is needed. But in my experience, helper methods, like right()
, make programs easier to develop.
Other methods, like between()
, before and after, are similar to right. They get substrings near known syntax parts. These are perhaps even more useful.
With right()
we extract the rightmost part of a string
. This utility method can make programs easier to develop (and understand afterwards). It is a substring-based method.