Here you can find the source of substring(final String s, int start)
Gets a substring from the specified String avoiding exceptions.
public static String substring(final String s, int start)
//package com.java2s; /**//from ww w . j av a 2 s . c o m * Copyright Sangram Jadhav. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Main { /** * <p> * Gets a substring from the specified String avoiding exceptions. * </p> * * <p> * A negative start position can be used to start {@code n} characters from * the end of the String. * </p> * * <p> * A {@code null} String will return {@code null}. An empty ("") String will * return "". * </p> * */ public static String substring(final String s, int start) { if (s == null) { return null; } // handle negatives, which means last n characters if (start < 0) { start = s.length() + start; // remember start is negative } if (start < 0) { start = 0; } if (start > s.length()) { return ""; } return s.substring(start); } /** * <p> * Gets a substring from the specified String avoiding exceptions. * </p> * * <p> * A negative start position can be used to start/end {@code n} characters * from the end of the String. * </p> * * <p> * The returned substring starts with the character in the {@code start} * position and ends before the {@code end} position. All position counting * is zero-based -- i.e., to start at the beginning of the string use * {@code start = 0}. Negative start and end positions can be used to * specify offsets relative to the end of the String. * </p> * * <p> * If {@code start} is not strictly to the left of {@code end}, "" is * returned. * </p> * */ public static String substring(final String s, int start, int end) { if (s == null) { return null; } // handle negatives if (end < 0) { end = s.length() + end; // remember end is negative } if (start < 0) { start = s.length() + start; // remember start is negative } // check length next if (end > s.length()) { end = s.length(); } // if start is greater than end, return "" if (start > end) { return ""; } if (start < 0) { start = 0; } if (end < 0) { end = 0; } return s.substring(start, end); } }