RSS

Insert delimiters between each character of a string

09 May

For example, to make the string “abcde” becomes “a,b,c,d,e” or “a b c d e”. What I’m going to do is to convert the string to a char array and then use String.Join to join the chars with the specific delimiters. There are different ways to accomplish it base on different versions of .NET Framework.

.NET 2.0
First using String.ToCharArray to convert the original string into a char array. Since String.Join takes a string array as the 2nd parameter, the char array needs to be converted into a string array. In .NET 2.0 we could use Array.ConverAll:

' Insert a space between each character of the passed in string parameter and
' return the result as a string
Private Function InsertSpaces(ByVal originalString As String) As String

    Dim newString As String

    Dim originalChars() As Char
    originalChars = originalString.ToCharArray()

    newString = String.Join(" ", _
        Array.ConvertAll(Of Char, String)(originalChars, _
                                          New Converter(Of Char, String)(AddressOf CharToString)))

    Return newString

End Function

Private Function CharToString(ByVal originalChar As Char) As String
    Return originalChar.ToString
End Function

.NET 3.5
In .NET 3.5 the String.Join can be simplified using Lambda expression:

Private Function InsertSpaces(ByVal originalString As String) As String

    Dim newString As String

    Dim originalChars() As Char
    originalChars = originalString.ToCharArray()

    ' Using Lambda expression
    newString = String.Join(" ", Array.ConvertAll(originalChars, Function(c) c.ToString())

    Return newString

End Function

Or using both LINQ and Lambda

    ' Using LINQ and Lambda expression
    newString = String.Join(" ", originalChars.Select(Function(c) c.ToString()).ToArray())

.NET 4.0
In .NET 4.0 we no longer need to convert the char array to a string array for String.Join:

Private Function InsertSpaces(ByVal originalString As String) As String

    Dim newString As String

    Dim originalChars() As Char
    originalChars = originalString.ToCharArray()

    newString = String.Join(" ", originalChars)

    Return newString

End Function

Reference: How to join int[] to a character separated string in .NET?

Advertisements
 
Leave a comment

Posted by on May 9, 2012 in .NET, Lambda, LINQ, VB

 

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: