String
has a constructorIt can be used in VB.NET programs. This allows you to convert a Char
array or single char
into a String
instance.
With the New String
syntax, you can create String
instances much faster than with the equivalent loop constructs. We can use the String
constructor after calling ToCharArray
.
First, this program is divided into 3 important routines. In the A subroutine, we show how to create a New String
from an entire character array.
String
by repeating the letter "a" ten times.String
instance from a range of a Char
array.String
constructors worked as expected.Module Module1 Sub Main() A() B() C() End Sub Sub A() ' Construct string from character array. Dim array(2) As Char array(0) = "a"c array(1) = "b"c array(2) = "c"c Dim example As String = New String(array) Console.WriteLine(example) Console.WriteLine(example = "abc") Console.WriteLine() End Sub Sub B() ' Construct string from repeated character. Dim example As String = New String("a"c, 10) Console.WriteLine(example) Console.WriteLine(example = "aaaaaaaaaa") Console.WriteLine() End Sub Sub C() ' Construct string from part of character array. Dim array(5) As Char array(0) = "a"c array(1) = "B"c array(2) = "c"c array(3) = "D"c array(4) = "e"c array(5) = "F"c Dim example As String = New String(array, 0, 3) Console.WriteLine(example) Console.WriteLine(example = "aBc") End Sub End Moduleabc True aaaaaaaaaa True aBc True
The string
constructor is different in the C# language and the VB.NET language. VB.NET does not allow you to use the unsafe (pointer-based) methods. The C# language allows you to.
The String
constructor provides an essential way to create certain kinds of strings. If you need a string
that is based on a range of Char
array, the String
constructor is ideal.