Android Question String function! replace group of chars with a single char

Beja

Expert
Licensed User
Longtime User
Hello friends,

I have a group of stars "********" in a string, and I want to replace them with a single star "*"
Is there any off-the-shelf function to do that?
Note: the group is variable but it is always more than 1.
Tanks in advance.
 

Mahares

Expert
Licensed User
Longtime User
Here is a weird way, but it might be all you need, unless you are looking for a more sophisticated way:
B4X:
Dim strVar As String="My name is Beja from the state of ********* located in the USA"
strVar=strVar.Replace(strVar.SubString2(strVar.IndexOf("*"),strVar.LastIndexOf("*")+1),"*")
Msgbox(strVar,"")  'displays only one star in sentence

Or if you want a function:
B4X:
Msgbox(ReplaceManyWithOne("My name is Beja from the state of ********* located in the USA","*"),"")  'displays only 1 star in sentence
B4X:
Sub ReplaceManyWithOne(strVar As String,MyChar As String) As String
    Return strVar.Replace(strVar.SubString2(strVar.IndexOf(MyChar),strVar.LastIndexOf(MyChar)+1),MyChar)
End Sub
 
Last edited:
Upvote 0

James Chamblin

Active Member
Licensed User
Longtime User
@Mahares, that wont work with strings such as "*I am ** and I am from ****, have a nice day*", everything between the first * and last * will be replaced by a single *. This version works by incrementally removing ** until none are left
B4X:
Dim strVar As String="*I am ** and I am from ****, have a nice day*"
Dim OldLength As Int = 0
Do While OldLength <> strVar.Length
   OldLength = strVar.Length
   strVar = strVar.Replace("**","*")
Loop
 
Upvote 0

Diabolus

Member
Licensed User
Longtime User
B4X:
Dim Txt As String = "***Regex *** is******** **your * * * friend**** ******** ** ***"
Dim Pattern As String = "([*])\1+"
Dim Replacement As String = "*"

Dim Matcher1 As Matcher
Matcher1 = Regex.Matcher(Pattern, Txt)

Dim r As Reflector
r.Target = Matcher1
Label1.Text = r.RunMethod2("replaceAll", Replacement, "java.lang.String")
 
Upvote 0

stevel05

Expert
Licensed User
Longtime User
Something a little more mundane:

B4X:
    Dim TestStr As String = "** Test *** Removal ***** ***"
    Log(RemoveDuplicates("*",TestStr))

Sub RemoveDuplicates(ThisChar As String, TargetString As String) As String

    Do While TargetString.Contains(ThisChar & ThisChar)
        TargetString = TargetString.Replace(ThisChar & ThisChar,ThisChar)
    Loop
    Return TargetString
End Sub
 
Upvote 0
Top