Android Code Snippet [B4X] Safer and more robust version of String SubString

Code: Copy
'Returns the substring from StartIndex up to, but excluding, EndIndex.
'Negative indices count back from the end. Omit EndIndex or pass 0 to include the rest of the string.
'Indices are clamped to the string bounds.
Public Sub SubString(s As String, StartIndex As Int, EndIndex As Int = 0) As String
    If StartIndex < 0 Then 
        StartIndex = Max(0, s.Length + StartIndex)
    Else
        StartIndex = Min(s.Length, StartIndex)
    End If
    If EndIndex <= 0 Then
        EndIndex = Max(0, s.Length + EndIndex)
    Else
        EndIndex = Min(s.Length, EndIndex)
    End If
    If EndIndex <= StartIndex Then Return ""
    Return s.SubString2(StartIndex, EndIndex)
End Sub

Code: Copy
Log(SubString("abc.def", 0)) 'abc.def
Log(SubString("abc.def", 0, 100)) 'abc.def
Log(SubString("abc.def", -4)) '.def
Log(SubString("abc.def", -3, -1)) 'de
Log(SubString("abc.def", 10, -1)) '<empty string>
Log(SubString("abc.def", 3, -1)) '.de

Useful when you want to trim a string to a maximum size without checking its actual length, and for easier access to the string suffix.
 
Great code. B4X is approaching python with codes like this.
 
Back
Top