Java String substring from middle
public class Main { public static void main(String[] args) { System.out.println("A --> " + getMiddleString("A")); System.out.println("AB --> " + getMiddleString("AB")); System.out.println("ABC --> " + getMiddleString("ABC")); System.out.println("ABCD --> " + getMiddleString("ABCD")); System.out.println("ABCDE --> " + getMiddleString("ABCDE")); System.out.println("ABCDEF --> " + getMiddleString("ABCDEF")); System.out.println("ABCDEFG --> " + getMiddleString("ABCDEFG")); }/*w ww . ja v a 2 s . c o m*/ public static String getMiddleString(String str) { if (str== null || str.length() <= 2) { return str; } int beginIndex = (str.length() - 1) / 2; int endIndex = beginIndex + 2 - (str.length() % 2); return str.substring(beginIndex, endIndex); } }
public class Main { public static void main(String[] argv) throws Exception { String str = "demo2s.com"; int pos = 2; int len = 2; System.out.println(mid(str, pos, len)); }//from www .j a v a 2 s. c om public static final String EMPTY = ""; /** * <p>Gets <code>len</code> characters from the middle of a String.</p> * * <p>If <code>len</code> characters are not available, the remainder * of the String will be returned without an exception. If the * String is <code>null</code>, <code>null</code> will be returned. * An exception is thrown if len is negative.</p> * * <pre> * mid(null, *, *) = null * mid(*, *, -ve) = "" * mid("", 0, *) = "" * mid("abc", 0, 2) = "ab" * mid("abc", 0, 4) = "abc" * mid("abc", 2, 4) = "c" * mid("abc", 4, 2) = "" * mid("abc", -2, 2) = "ab" * </pre> * * @param str the String to get the characters from, may be null * @param pos the position to start from, negative treated as zero * @param len the length of the required String, must be zero or positive * @return the middle characters, <code>null</code> if null String input */ public static String mid(String str, int pos, int len) { if (str == null) { return null; } if (len < 0 || pos > str.length()) { return EMPTY; } if (pos < 0) { pos = 0; } if (str.length() <= (pos + len)) { return str.substring(pos); } return str.substring(pos, pos + len); } }