Skip to content

StringUtils.substring

Signature: StringUtils.substring(inputString, startPosition, endPosition*)

Returns: String result - the substring from startPosition to endPosition, or null if inputString is null

Gets a substring from the specified inputString avoiding exceptions. A negative startPosition or endPosition can be used to start n characters from the end of the String. The returned substring starts with the character in the startPosition and ends before the endPosition. All position counting is zero-based -- i.e., to start at the beginning of the string use startPosition = 0. Negative start and end positions can be used to specify offsets relative to the end of the String.

Parameters

Type Name Description Default
String inputString the String to get the substring from, may be null
Integer startPosition the position to start from, negative means count back from the end of the String by this many characters
Integer endPosition* (optional) the position to end at (exclusive), negative means count back from the end of the String by this many characters length of inputString

Example

// Basic usage: [start, end) (end is exclusive)
StringUtils.substring("I love to eat apples!", 0, 6);      // "I love"

// endPosition beyond length clamps to end (no exception)
StringUtils.substring("I love to eat apples!", 14, 7777);  // "apples!"
StringUtils.substring("I love to eat apples!", 14);        // "apples!"

// Negative endPosition counts back from end (end still exclusive)
StringUtils.substring("I love to eat apples!", 0, -7);     // "I love to eat "

// Negative startPosition counts back from end
StringUtils.substring("I love to eat apples!", -7);        // "apples!"