Char Combine: Get String From CharsCreate a String from multiple Chars by creating a Char array and converting the array to a String.
This page was last reviewed on Dec 3, 2023.
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.
Char Array
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.
Part 1 Here we declare 4 separate Chars and pass them to the CharCombine function, which returns a String with the merged characters.
Part 2 A separate Function is not necessary, and it may be best to do the conversion inline. Here we convert 2 Chars into a String.
Part 3 We can call ToString on each Char, and then concatenate the Strings into a new String, but this involves more complexity and is slower.
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 Module
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.
This page was last updated on Dec 3, 2023 (new).
© 2007-2024 Sam Allen.