is it possible to insert a character say " " (space) after every 2 characters in a string?

using this doesnt seem to work :

Dim s As String

s = "010001000100"



s = Mid(s, 1, 2) & " " & Mid(s, 4)
MsgBox s

it adds space only after first two chars

Recommended Answers

All 2 Replies

You have to loop the original string:

Private Function InsertChar(ByVal StringIn As String, _
  ByVal CharToInsert As String, _
  ByVal InsPosition As Integer) As String
  
  Dim NewString As String
  Dim CharsUsed As Integer
  Dim i As Integer
  
  If InsPosition >= Len(StringIn) Then
    InsertChar = StringIn
    Exit Function
  End If
  NewString = ""
  CharsUsed = 0
  i = 1
  Do Until i >= Len(StringIn)
    NewString = NewString & Mid(StringIn, i, InsPosition) & CharToInsert
    CharsUsed = CharsUsed + InsPosition
    If i + InsPosition >= Len(StringIn) And CharsUsed < Len(StringIn) Then
      NewString = NewString & Mid(StringIn, CharsUsed + 1, Len(StringIn) - CharsUsed)
    End If
    i = i + InsPosition
  Loop
  InsertChar = NewString

End Function

You may also want to change If InsPosition >= Len(StringIn) Then to If InsPosition >= Len(StringIn) - 1 Then if you don't want to insert character after the whole string. I mean that the function returns now InsertChar("ABCD", "#", 2) -> "AB#CD#" and InsertChar("ABCDE", "#", 2) -> "AB#CD#E".

commented: GREAT! +1

Thanx a lot for the tips! Really helpful :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.