Java Left / Right / Mid String Functions (as in Visual Basic.Net)

Visual Basic’s left, right, mid functions are nifty tricks that can be easily implemented in Java.

package test;

public class Test {
    public static String left(String input, int len) {
        return input.substring(0, len);
    }
    
    public static String right(String input, int len) {
        return input.substring(input.length() - len);
    }

    public static String mid(String input, int index, int len) {
        return input.substring(index - 1, index + len - 1);
    }

    public static String mid(String input, int index) {
        return input.substring(index - 1);
    }
    
    public static void main(String[] args) {
        String str1 = "left string";
        System.out.println("Test left str: " + str1);
        System.out.println("Test left str: " + left(str1, 4));    

        String str2 = "right string";
        System.out.println("Test right str: " + str2);
        System.out.println("Test right str: " + right(str2, 6));    

        String str3 = "mid string";
        System.out.println("Test mid str: " + str3);
        System.out.println("Test mid str: " + mid(str3, 2, 6));    

        System.out.println("Test mid str: " + str3);
        System.out.println("Test mid str: " + mid(str3, 5));
    }
}

Output:
Test left str: left string
Test left str: left
Test right str: right string
Test right str: string
Test mid str: mid string
Test mid str: id str
Test mid str: mid string
Test mid str: string

Leave a Reply