Get String substring - Java java.lang

Java examples for java.lang:String Substring

Description

Get String substring

Demo Code

public class Main {

  public static void main(String[] argv) {
    String str = "java2s.com";
    int start = 2;
    System.out.println(substring(str, start));
  }/*from w w  w. jav a2s. c om*/

  public static final String EMPTY = "";

  public static String substring(String str, int start, int end) {
    if (str == null) {
      return null;
    }

    // handle negatives
    if (end < 0) {
      end = str.length() + end; // remember end is negative
    }
    if (start < 0) {
      start = str.length() + start; // remember start is negative
    }

    // check length next
    if (end > str.length()) {
      end = str.length();
    }

    // if start is greater than end, return ""
    if (start > end) {
      return EMPTY;
    }
    if (start < 0) {
      start = 0;
    }
    if (end < 0) {
      end = 0;
    }
    return str.substring(start, end);
  }

  public static String substring(String str, int start) {
    if (str == null) {
      return null;
    }

    // handle negatives, which means last n characters
    if (start < 0) {
      start = str.length() + start; // remember start is negative
    }
    if (start < 0) {
      start = 0;
    }
    if (start > str.length()) {
      return EMPTY;
    }
    return str.substring(start);
  }

}

Related Tutorials