Question How do i add a space between every character in a string?

joeinnes

New member
Joined
Oct 7, 2009
Messages
4
Programming Experience
1-3
How do I add a space between every character in a string of text?
For example:
Change "abcdefg"
To "a b c d e f g"

I have two text boxes on my form, one for input, the other for output of the re-formatted string.
Some code would be really helpful! Thanks in advance. :D
 
To insert in a String you can use the String.Insert method:
VB.NET:
Dim s As String = "abcdefg"
For i As Integer = s.Length - 1 To 1 Step -1
    s = s.Insert(i, " ")
Next
 
Thanks so much!
i had tried the string.insert method with a loop, but couldn't get it to work!
I've never used a forum before, as i imagined them as question asking things, where your questions aren't answered for years!
Thanks for the fast reply-it was urgent!!
:D
 
Well, welcome to the forums, some questions goes unanswered.

A forward For-Next loop would not work because the counter limits is only evaluated once, but a Do-Loop is doable with a few more lines of code. In VB 2008 you can also do this; convert the Char array to a String array and String.Join it:
VB.NET:
s = String.Join(" ", Array.ConvertAll(s.ToCharArray, Function(c) c.ToString))
 
Regex.Replace("your string", "(.)", "$1 ")

Or this, abusing the fact that unicode stores 2 bytes:
System.Text.Encoding.ASCII.GetString(System.Text.Encoding.Unicode.GetBytes("your string")).Replace(Convert.ToChar(0), " "c)
 
Back
Top