String Right Part
This page was last reviewed on Sep 21, 2023.
Dot Net Perls
String right. A string contains important characters on its end (the right side). With a custom method, we can easily extract these characters.
Method notes. 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.
Input and output. 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.
String substring
Right(4) Input = "website" Output = "site"
Example program. 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.
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 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.
String Between
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2024 Sam Allen.