Java String Sub String substring(String s, int start, int length)

Here you can find the source of substring(String s, int start, int length)

Description

Extract a substring from the given string, using start index and length of the extracted substring.

License

Open Source License

Parameter

Parameter Description
s the original String
start starting position for the substring within the original string. 0-based index position
length length in characters of the substracted substring

Return

the resulting String

Declaration

static String substring(String s, int start, int length) 

Method Source Code

//package com.java2s;
/*//from w ww . j av a2 s  . c  o m
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */

public class Main {
    /**
     * Extract a substring from the given string, using start index and length of the extracted substring.
     *
     * @param s       the original String
     * @param start   starting position for the substring within the original string. 0-based index position
     * @param length  length in characters of the substracted substring
     * @return the resulting String
     */
    static String substring(String s, int start, int length) {
        if (!hasLength(s)) {
            return s;
        }

        if (start < 0)
            start = 0;

        if (start + 1 > s.length() || length < 0)
            return "";

        return (start + length > s.length()) ? s.substring(start) : s.substring(start, start + length);
    }

    private static boolean hasLength(String s) {
        return (s != null && s.length() > 0);
    }
}

Related

  1. substring(String S, int beginIndex, int endIndex)
  2. substring(String s, int beginIndex, int endIndex)
  3. substring(String s, int i, String substring, int direction)
  4. subString(String s, int length)
  5. substring(String s, int start)
  6. substring(String s, int start, int stop)
  7. subString(String s, int startIndex, int count)
  8. substring(String self, Integer startIndex, Integer endIndex)
  9. substring(String source, int beginIndex, int endIndex)