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
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,332
Location
Norway
Programming Experience
10+
To insert in a String you can use the String.Insert method:
Code:
Dim s As String = "abcdefg"
For i As Integer = s.Length - 1 To 1 Step -1
    s = s.Insert(i, " ")
Next
 

joeinnes

New member
Joined
Oct 7, 2009
Messages
4
Programming Experience
1-3
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
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,332
Location
Norway
Programming Experience
10+
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:
Code:
s = String.Join(" ", Array.ConvertAll(s.ToCharArray, Function(c) c.ToString))
 

cjard

Well-known member
Joined
Apr 25, 2006
Messages
7,052
Programming Experience
10+
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)
 
Top Bottom