removes a number of characters from the beginning and the end of a string - Java java.lang

Java examples for java.lang:String Truncate

Description

removes a number of characters from the beginning and the end of a string

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String s = "java2s.com";
        int numStart = 2;
        int numEnd = 4;
        System.out.println(strip(s, numStart, numEnd));
    }/*from   w w  w  .j  a  v a 2 s  .c  o m*/

    /**
     * removes a number of characters from the beginning and the end of a string
     */
    public static String strip(String s, int numStart, int numEnd) {
        if (s == null)
            return s;

        return substring(s, numStart, s.length() - numEnd);
    }

    /**
     * same as String.substring, except that this version handles the case
     * robustly when the index is out of bounds.
     */
    public static String substring(String str, int beginIndex) {
        if (str == null)
            return null;
        if (beginIndex < 0)
            return str;
        if (beginIndex >= str.length())
            return "";

        return str.substring(beginIndex);
    }

    /**
     * same as String.substring, except that this version handles the case
     * robustly when one or both of the indexes is out of bounds.
     */
    public static String substring(String str, int beginIndex, int endIndex) {
        if (str == null)
            return null;
        if (beginIndex > endIndex)
            return "";
        if (beginIndex < 0)
            beginIndex = 0;
        if (endIndex > str.length())
            endIndex = str.length();

        return str.substring(beginIndex, endIndex);
    }
}

Related Tutorials