B4J Question Splitting an empty TextField.Text

LucaMs

Expert
Licensed User
Longtime User
B4X:
    'TextField1.Text is empty - just loaded the layout.

    'Logs zero.
    Log("TextField1.Text.Length = " & TextField1.Text.Length)

    Dim str() As String = Regex.Split(",", TextField1.Text)

    'Logs 1 instead of zero.
    Log("str length = " & str.Length)


EDIT:
Dim str() As String = Regex.Split(",", "")
does the same.
 
Last edited:
1669379925247.png
 
Last edited:
Upvote 0
The java string split function returns a string array with one element that contains the original text if there was no match found.
And that one element can of course be empty.

Java:
           // If no match was found, return this
            if (off == 0)
                return new String[]{this};

B4X:
    'TextField1.Text is empty - just loaded the layout.
   
    Log("*" & TextField1.Text & "*")
    'Logs zero.
    Log("TextField1.Text.Length = " & TextField1.Text.Length)
   
    TextField1.Text = "some text without a comma"
   
    Dim str() As String = Regex.Split(",", TextField1.Text)
    Dim lst As List = Regex.Split(",", TextField1.Text)

    'Logs 1 instead of zero.
    Log("str length = " & str.Length)
    Log("list size = " & lst.size)
    Log("*" & str(0) & "*")
    Log("*" & lst.Get(0) & "*")
 
Upvote 0
If you squint hard enough, it does match the documentation: for an empty string, there are no matches at all, let alone trailing empty matches to remove ?

B4X:
Dim TestCases() As String = Array As String( _
    ",,,"      , _
    ",,"       , _
    ","        , _
    ""         , _
    ",,, ,,,"  , _
    ",, ,,"    , _
    ", ,"      , _
    " ,"       , _
    ", "       , _
    " , "        _
)

For Each S As String In TestCases
    Log("""" & S & """" & TAB & Regex.Split(",", S).Length)
Next

[CODE lang="JSON" title="Log output"]Waiting for debugger to connect...
Program started.
",,," 0
",," 0
"," 0
"" 1
",,, ,,," 4
",, ,," 3
", ," 2
" ," 1
", " 2
" , " 2
Program terminated (StartMessageLoop was not called).[/CODE]
 
Last edited:
Upvote 0
Back
Top