Sub AddDash(Text As String) As String
Dim StrinParts As List
StrinParts.Initialize
Do While Text.Length >= 4
StrinParts.Add(Text.SubString2(0,4))
Text = Text.SubString(4)
Loop
If Text.Length > 0 Then StrinParts.Add(Text)
Dim NewText As String = StrinParts.Get(0)
For i = 1 To StrinParts.Size -1
NewText = NewText & "-" & StrinParts.Get(i)
Next
Return NewText
End Sub
Dim str As String="1234567812345678"
Dim dashed As String
For x=0 To str.Length-1
dashed=dashed & str.CharAt(x)
If x Mod 4=3 And x<str.Length-1 Then dashed=dashed &"-"
Next
Log(dashed)
and if you like regex this should work too
B4X:
Dim str As String="1234567812345678"
Dim rm As Matcher
rm=Regex.Matcher("(\d{4})(\d{4})(\d{4})(\d{4})",str)
rm.Find
Log(rm.Group(1)&"-"&rm.Group(2)&"-"&rm.Group(3)&"-"&rm.Group(4))
You should avoid concatenating immutable strings. If the strings are short then it doesn't matter. However if the strings can be large then the difference will be significant.
Better solution:
B4X:
Sub AddDashes(s As String) As String
Dim sb As StringBuilder
sb.Initialize
For i = 0 To s.Length - 5 Step 4
sb.Append(s.SubString2(i, i + 4))
sb.Append("-")
Next
sb.Append(s.SubString2(i, s.Length))
Return sb.ToString
End Sub
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.