Android Question My recursive function not working as expected

toby

Well-Known Member
Licensed User
Longtime User
I created the following recursive function to remove all occurrences of matching chars from the string. The log indicates the function get the result correctly, but the final result returned is empty
. Could someone kindly point me to the mistakes I've made, please?

calling code:
Dim result As String=StringHelper.RemoveChars("to see is to believe", "to") 'expected result: " see is  believe" with both "to" removed
LogColor(result, Colors.Blue )  'nothing was printed

Recursive function:
'Remove all occurrences of chars in the Str string
Sub RemoveChars(str As String, chars As String) As String
    Dim i As Int=str.IndexOf(chars)
    If i>=0 Then
        Dim sb As StringBuilder
        sb.Initialize
        sb.Append(str)
        sb.Remove(i, i +chars.Length)
        LogColor("New str=" & sb.ToString, Colors.blue) 'correct result is logged here
        RemoveChars(sb.ToString, chars)  'recursive
    Else
        Return str  'escape
    End If
End Sub
 

Star-Dust

Expert
Licensed User
Longtime User
B4X:
'Remove all occurrences of chars in the Str string
Sub RemoveChars(str As String, chars As String)ti","") As String
    Dim i As Int=str.IndexOf(chars)
    If i>=0 Then
        Dim sb As StringBuilder
        sb.Initialize
        sb.Append(str)
        sb.Remove(i, i +chars.Length)
        LogColor("New str=" & sb.ToString, Colors.blue) 'correct result is logged here
        Return RemoveChars(sb.ToString, chars)  'recursive
    Else
        Return str  'escape
    End If
End Sub

Buy Is more simple method Replace:
String.Replace("to","")
 
Upvote 0
Top