This Sub Counts Occurencnes of a Character Pattern in a string and returns the result as an Integer.
Example:
Log(CountOccurences("is", "This is a Simple Subroutine"))
Result: 2
The Split(sPattern, sText) subroutine functions as regex.Split but sPattern can be a string of characters
Example:
Dim txtParts() as string
Dim i as Int
txtParts = Split("is", "Peter is 5 years old but Peter is very tall")
for i = 0 to txtParts.Length - 1
log(txtParts(i))
next i
Result:
Peter
is 5 years old but Peter
is very tall
Example:
Log(CountOccurences("is", "This is a Simple Subroutine"))
Result: 2
B4X:
Sub CountOccurences(sPattern As String, sText As String) As Int
Dim sPatternLength, sTextLength As Int
Dim i As Int
Dim result As Int
sPatternLength = sPattern.Length
sTextLength = sText.Length
result = 0
For i = 0 To sTextLength - sPatternLength
If sPattern = sText.SubString2(i, i + sPatternLength) Then
result = result + 1
End If
Next
Return result
End Sub
The Split(sPattern, sText) subroutine functions as regex.Split but sPattern can be a string of characters
Example:
Dim txtParts() as string
Dim i as Int
txtParts = Split("is", "Peter is 5 years old but Peter is very tall")
for i = 0 to txtParts.Length - 1
log(txtParts(i))
next i
Result:
Peter
is 5 years old but Peter
is very tall
B4X:
Sub Split(sPattern As String, sText As String) As String()
Dim TextBuffer() As String
Dim intFirstIndex As Int
Dim intLastIndex As Int
Dim i As Int
sText = sText.Replace(sPattern,"~")
intFirstIndex = sText.IndexOf("~")
intLastIndex = sText.LastIndexOf("~")
TextBuffer = Regex.Split("~", sText)
If TextBuffer.Length > 0 Then
For i = 1 To TextBuffer.Length - 1
TextBuffer(i) = sPattern & TextBuffer(i)
Next
If intFirstIndex = intLastIndex AND TextBuffer.Length = 1 Then
TextBuffer(0) = TextBuffer(0) & sPattern
End If
If intFirstIndex = 0 AND TextBuffer.Length > 1 Then
Dim ReTextBuffer() As String
ReTextBuffer = TextBuffer
Dim Textbuffer(ReTextbuffer.Length - 1) As String
Dim k As Int
k = 0
For i = 0 To ReTextBuffer.Length - 1
If ReTextBuffer(i).Trim.Length > 0 Then
TextBuffer(k) = ReTextBuffer(i)
k = k + 1
End If
Next
End If
If intFirstIndex = -1 AND intLastIndex =-1 Then
Dim TextBuffer() As String
End If
Else
Dim TextBuffer() As String
End If
Return TextBuffer
End Sub
Last edited: