Java String Sub String substring(final String text, final int position, final int length)

Here you can find the source of substring(final String text, final int position, final int length)

Description

Return substring of text.

License

Open Source License

Parameter

Parameter Description
text Text to work on. Must not be <code>null</code>.
position Starting position. Might be negative.
length Maximum length to get.

Exception

Parameter Description
NullPointerException <code>text</code> is <code>null</code>.

Return

Substring of maximum length length and starting with position.

Declaration

public static String substring(final String text, final int position, final int length) 

Method Source Code

//package com.java2s;
/* This file is part of the project "Hilbert II" - http://www.qedeq.org
 *
 * Copyright 2000-2013,  Michael Meyling <mime@qedeq.org>.
 *
 * "Hilbert II" is free software; you can redistribute
 * it and/or modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *///from w w  w.  j ava 2s . c  o  m

public class Main {
    /**
     * Return substring of text. Position might be negative if length is big enough. If the string
     * limits are exceeded this method returns at least all characters within the boundaries.
     * If no characters are within the given limits an empty string is returned.
     *
     * @param   text        Text to work on. Must not be <code>null</code>.
     * @param   position    Starting position. Might be negative.
     * @param   length      Maximum length to get.
     * @return  Substring of maximum length <code>length</code> and starting with position.
     * @throws  NullPointerException    <code>text</code> is <code>null</code>.
     */
    public static String substring(final String text, final int position, final int length) {
        final int start = Math.max(0, position);
        int l = position + length - start;
        if (l <= 0) {
            return "";
        }
        int end = start + l;
        if (end < text.length()) {
            return text.substring(start, end);
        }
        return text.substring(start);
    }
}

Related

  1. substring(final String s, int start)
  2. substring(final String s, int start, int end)
  3. substring(final String s, int startIndex, int endIndex)
  4. substring(final String str, int start, int end)
  5. substring(final String string, int fromIndex, int toIndex)
  6. substring(String _text, int _idx)
  7. substring(String baseString, int start, int end)
  8. subString(String input, char start, char end)
  9. substring(String input, int expectedLength)