Slicing Strings

Prev Next

Introduction

Instead of specifying single index values to retrieve single characters, substrings can be retrieved by listing muliple values and/or ranges. In some other programming langauges, this feature is known as slicing. The range operator '..' is available to specify a range. If no value prcedes the range operator, than 0 is assumed. If no value follows the range operator, then the last character is assumed. The result will always be a string. Negative indexing is supported.

       echo( abcdefg { 0,2,4,2,0 } );    // Returns 'aceca'
       echo( abcdefg { 3..5 } );         // Returns 'def'
       echo( abcdefg { 5..3 } );         // Empty string.  Ranges cannot be listed in reverse direction
       echo( abcdefg { -3..-1 } );       // Returns 'efg' - Last 3 characters
       echo( abcdefg { 4..-1 } );        // Same result
       echo( abcdefg { 3..99 } );        // Returns 'defg'
       echo( abcdefg { -99..2 } );       // Returns 'abc'
       echo( abcdefg { 0..2,5,1..3 } );  // Combinations
       echo( abcdefg { 3.. } );          // Returns 'defg'
       echo( abcdefg { ..3 } );          // Returns 'abcd'
       echo( abcdefg { .. } );           // Returns full string
       echo( abcdefg { ..,.. } );        // Returns full string twice: abcdefgabcdefg
aceca
def

efg
efg
defg
abc
abcfbcd
defg
abcd
abcdefg
abcdefgabcdefg
Try it yourself: Open LAN_Features_Slicing_strings.b4p in B4P_Examples.zip. Decompress before use.