Char combine. In many VB.NET programs, we may have some Char values we want to convert into a single String. We can combine these Chars into a String in a variety of ways.
By creating a Char array, we can place each Char in an element of the array. Then we can convert the array to a String with the String constructor.
Example. We introduce a function called CharCombine in this VB.NET module. CharCombine contains the logic for combining 4 Chars into a String. Any number of Chars could be combined.
Module Module1
Function CharCombine(c1 as Char, c2 as Char, c3 as Char, c4 as Char) as String
' Create array by specifying last valid index as size.
Dim result(3) as Char
result(0) = c1
result(1) = c2
result(2) = c3
result(3) = c4
Return New String(result)
End Function
Sub Main()
' Part 1: use function to combine 4 Chars into a string.
Dim c1 as Char = "a"c
Dim c2 as Char = "b"c
Dim c3 as Char = "c"c
Dim c4 as Char = "d"c
Dim resultFromFunction = CharCombine(c1, c2, c3, c4)
Console.WriteLine("FUNCTION RESULT: [{0}]", resultFromFunction)
' Part 2: place code inline to convert from 2 chars to a string.
Dim result(1) as Char
result(0) = "x"c
result(1) = "y"c
Dim resultString = New String(result)
Console.WriteLine("RESULT: [{0}]", resultString)
' Part 3: use calls to ToString and concatenate them.
Dim resultSlow = c1.ToString() + c2.ToString() + c3.ToString()
Console.WriteLine("TOSTRING: [{0}]", resultSlow)
End Sub
End ModuleFUNCTION RESULT: [abcd]
RESULT: [xy]
TOSTRING: [abc]
For situations where performance does not matter, calling ToString on each Char and then using "+" to concat the strings is acceptable. But this code involves another layer of conversion.
And In my benchmarks, it is consistently faster to just use a Char array of the appropriate size for this conversion.
Summary. For converting Chars into Strings, we can use a Char array and then the String constructor. This works for any number of Chars—and we can even use For-loops to fill the Char array.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.