| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Navigation |
Synopsis Retrieve a slice of a string.
Syntax
Exp_{2} and Exp_{4} are optional.
Types
Description A String slice is similar to a list Slice and uses the integer values of
Exp_{2} and Exp_{4} to determine the begin (inclusive) and end (exclusive)
of a slice from the string value S of Exp_{1} . Negative indices count from the end of the string backwards.
Using the second form, an extra index Exp_{3} is given that determines the
index of the second element in the slice and establishes the step between
successive elements in the slice. The default step is 1.
If end is smaller than begin , the slice is constructed backwards.
Let Len be the length of S and let N_{2} , N_{3} and N_{4} be the respective values of the expressions
Exp_{2} , Exp_{2} and Exp_{2} when they are present.
The slice parameters begin , end , and step are determined as follows:
0 <= begin < Len and 0 < end < Len should hold,
otherwise the exception IndexOutOfBounds is thrown.
The slice consists of the elements S[begin] , S[begin+step] , S[end - step] .
When begin >= end , the elements are listed in reverse order.
Examples Consider the string
S = "abcdefghi"; (with size 9) as running example.
Here is a view on L that will help to correlate positive and negative indices:
Some common use cases (with begin <= end ):
rascal>S = "abcdefghi";
str: "abcdefghi"
Slices with begin < end
rascal>S[1..3]; str: "bc" rascal>S[1..]; // empty end => end of string str: "bcdefghi" rascal>S[..3]; // empty begin => first character of string str: "abc" rascal>S[..]; // both empty => whole string str: "abcdefghi"Slices with begin >= end rascal>S[3..1]; // slice contains characters with indices 3 and 2 (in that order) str: "dc" rascal>S[3..3]; // empty slice when begin == end str: ""Slices with negative begin or end: rascal>S[2..-2]; // equivalent to S[2..7] str: "cdefg" rascal>S[2..7]; str: "cdefg" rascal>S[-4..-2]; // equivalent to S[5..7] str: "fg" rascal>S[5..7]; str: "fg"Slices with an explicit second index: rascal>S[1,3..6]; str: "bdf" rascal>S[5,3..]; str: "fdb"Explore error cases: rascal>S[..10]; |stdin:///|(4,2,<1,4>,<1,6>): IndexOutOfBounds(10) at ___SCREEN_INSTANCE___(|stdin:///|(0,8,<1,0>,<1,8>)) rascal>S[1..20]; |stdin:///|(5,2,<1,5>,<1,7>): IndexOutOfBounds(20) at ___SCREEN_INSTANCE___(|stdin:///|(0,9,<1,0>,<1,9>)) |