0

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

2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by ChroNoS
1

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".

Votes + Comments
GREAT!
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.