Java Right String Part

Get the right characters from a string with a custom right method. Use substring to implement the logic.
String right. A 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.
The program here implements a right method. Right() calls substring in its implementation. It computes the beginning by subtracting the argument (the count of chars) from the string length.

Thus: The call to right will extract the specified number of characters from the end of the string, and return it as a new string.

Result: With an argument of 4, right() returns the last four chars of a string. With 7, it returns the last seven chars.

Java program that uses right method, gets rightmost 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); } } Output site Machine
A substring helper. 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. Other methods, like between(), before and after, are similar to right. They get substrings near known syntax parts. These are perhaps even more useful.Between, Before, After
A review. 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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls