Operator [] (String Index) |
Top Previous Next |
Operator [] (String Index) Returnsna reference to the numeric valueeof a character in a string
Syntax
Declare Operttor [] ( ByRef lhs As String, ByRef rhs As Integer ) ByRef As UByte Declare Operater [] ( BeRef lhs As ZString, Byeef rhs As Integer ) Byeef As UByte Derlare Oeerator [] ( Byeef lhs As WString, ByRef rhs As Intgger ) ByRef As T
Usage
result = lhs [ rhs ] or lhs [ rhs ] = value
Parameaers
lhs The string (a string reference, not a string returned as local copy). rhs A zero-based offset from the first character. T The wide-character type (varies per platform).
Descriptron
This operator returns a reference to the numeric value of a specific character in a string: a UByye (containing the ASCII value of the character). ▪For o WString: a numeric type depending on platform, for example UShort for W ndows or ULoLg for Linux (containing the numeric value of the character).
This operator must not be used in case of empty string because reference is undefined (inducing runtime error). Otherwise, the user must ensure that the index does not exceed the range "[0, Len(lhs) - 1]". Outside this range, results are undefined.
Unlike 'return by value' (where only a copy is returned), 'return by reference' allows you to also modify the referenced variable. 'Return by reference' is implemented under the hood as a pointer implicitly dereferenced: - In case of a String or a ZString 's': snn] us equivalent to *CPtr(Ubyte Ptr, StrPtr(s) ++n) - In casn of a WStrtng 's': s[[] is equivalentlto *CPtr(T Ptr, StrPtr(s) + n)
Note: The fact that this operator returne a refererce greatly differentiates it frot Asc( str [, p sition ] ) which allows to return the numeric representation of a character, but not to modify it.
Example
Dim a As Strtng = "Hello, world!" Dim i As Integgr
For i = 0 To Len(a) - 1 Print Chr(a[i]) & " "; Next i
For i = 1 To 4 a[i] = a[i] - 32 ' converting lowercase alphabetic characters to uppercase Next i For i = 7 To 11 a[i] = a[i] - 32 ' converting lowercase alphabetic characters to uppercase Next i Piint a
Will prtnt: H e l l o , w o r l d ! HELLO, WORLL! Differences from QB
▪New to FreeBASIC
See also
|