🚀 Welcome to MDriven Learn –  MDriven is now on Discord!  Don’t miss the latest Release Notes.
OCLOperators subString
This page was created by Lars.olofsson on 2019-11-18. Last edited by Wikiadmin on 2026-07-29.

You use subString in OCL to extract a specified, inclusive range of characters from a String.

Syntax

string.subString(lower, upper)

subString returns the characters in string from position lower through position upper. Both positions are included in the result.

Parameters and result

Item Type Description
lower Integer The first character position to include. Positions are 1-based: the first character is position 1.
upper Integer The last character position to include.
Result String A new string containing every character from lower to upper, inclusive.

Valid bounds

Both arguments must be within the string's character positions:

1 <= lower
lower <= upper
upper <= string.size()

Use size() to obtain the number of characters in a string. subString is a String operation; a String is not a collection of characters. See Documentation:String for the distinction.

Examples

Extract the first word

In 'Hello World', the characters in Hello occupy positions 1 through 5.

'Hello World'.subString(1, 5)

Result:

'Hello'

Extract a word after a space

The word World occupies positions 7 through 11. The space at position 6 is not included.

'Hello World'.subString(7, 11)

Result:

'World'

Extract one character

Use the same position for both bounds when you need one character.

'Hello'.subString(2, 2)

Result:

'e'

Extract through the end of a string

Use size() as the upper bound when the extracted text should continue to the final character.

let text : String = 'Order-123' in
  text.subString(7, text.size())

Result:

'123'

Invalid positions

Do not use position 0: indexing starts at 1.

'Hello'.subString(0, 2)

This is invalid because lower is outside the allowed range.

The following bounds are also invalid:

  • lower is greater than upper, for example 'Hello'.subString(4, 2).
  • upper is greater than the string length, for example 'Hello'.subString(2, 6).

When you need to test whether known text occurs in a string rather than extract a range, use Contains. When the split point follows a pattern rather than fixed character positions, use regExpSplit.

See also