Indexing Strings

Prev Next

Introduction

Simple indexing is used to retrieve single characters from the string. Indexing begins with 0 which refers to the 1st character. The index value is specified in braces added behind the string value, string variable or expression providing a string.

Following rules apply to the indexing strings:

  • The index must always be a numeric value.
  • Specifying just braces {} without an index will retrieve the length (character count). Alternatively, use length [string function].
  • Indexing begins with 0 (zero).
  • The value will be rounded in case it does not contain an integer value. Example: a[]{2.99} accesses the same member as a[3].
  • Negative indexing is supported. -1 refers to the last character in the string. -2, -3, etc. refer to the previous ones, and so forth.
  • Updating individual characters in the string on the left hand side of assignments is not possible. Wrong exmaple: a[]{3} = 'E';.

       echo( abcde{} );     // Returns 5 (character count)
       echo( abcde{0} );   // Access the 1st element
       echo( abcde{-2} );  // Access the 2nd last element
       echo( abcde{10} );  // Attempts to access characters outside the string returns blank strings.
       echo( abcde{-10} ); // Same case here.
Output:
5
a
d


Try it yourself: Open LAN_Features_Indexing_strings.b4p in B4P_Examples.zip. Decompress before use.