B4J Question how to find intervals i a string?

emexes

Expert
Licensed User
Is the next step to divide the string, splitting it at each space?

What if there are two spaces together? Is there an empty (zero length) field between the two spaces?

What about leading and trailing spaces?

Your simplest solution might be Regex.Split:

B4X:
LogStringArray(Regex.Split(" ", "Now is the time"))
LogStringArray(Regex.Split(" ", " for all good men "))
LogStringArray(Regex.Split(" ", "to come to the"))
LogStringArray(Regex.Split(" ", " aid of the party."))

Sub LogStringArray(S() As String)

    Log("Split into " & S.Length & " substrings")
    For I = 0 To S.Length - 1
        Log(I & TAB & """" & S(I) & """")
    Next
 
End Sub
Log output:
Split into 4 substrings
0    "Now"
1    "is"
2    "the"
3    "time"
Split into 5 substrings
0    ""
1    "for"
2    "all"
3    "good"
4    "men"
Split into 4 substrings
0    "to"
1    "come"
2    "to"
3    "the"
Split into 5 substrings
0    ""
1    "aid"
2    "of"
3    "the"
4    "party."
 
Last edited:
Upvote 0

emexes

Expert
Licensed User
Your simplest solution might be Regex.Split:
1734874335577.png
 
Upvote 0
in VB my code was
For i = 1 To Len(ArG)
If Mid(ArG, i, 1) = " " Then
BrIntervali = BrIntervali + 1
End If
Next i
First of all, thank you very much for your answers.
I did it like this after searching the forum...
my example:
Sub interval(mstr As String) As Int
    
    Dim pattern As String
    pattern = " "
    Dim Matcher1 As Matcher
    Dim i As Int
    i=0
    Matcher1 = Regex.Matcher(pattern, mstr)
        Do While Matcher1.Find
            i=i+1
            Log("Found: " & i)
            Log("----: " & Matcher1.Match)
        Loop
    Return i   
End Sub
 
Upvote 0

emexes

Expert
Licensed User
my example:
Sub interval(mstr As String) As Int
   
    Dim pattern As String
    pattern = " "
    Dim Matcher1 As Matcher
    Dim i As Int
    i=0
    Matcher1 = Regex.Matcher(pattern, mstr)
        Do While Matcher1.Find
            i=i+1
            Log("Found: " & i)
            Log("----: " & Matcher1.Match)
        Loop
    Return i  
End Sub

If you just wanted a count then you could do:
B4X:
Sub interval(mstr As String) As Int
    Return Regex.Split(" ", mstr.Trim).Length
End Sub
 
Upvote 0

emexes

Expert
Licensed User
I usually use Regex.Split because it puts all the fields (substrings) into an array ready for whatever the next processing step is.

The .Trim removes leading and trailing spaces.

You can just as easily use commas or semicolons or tabs as separators.
 
Upvote 0
Top