How to convert string to string array in VB.NET?

22,705

Solution 1

With VB10, you can simply do this:

func({str})

With an older version you'll have to do:

func(New String() {str})

Solution 2

Just instantiate a new array including only your string

Sub Main()
    Dim s As String = "hello world"
    Print(New String() {s})
End Sub

Sub Print(strings() As String)
    For Each s In strings
        Console.WriteLine(s)
    Next
End Sub

Solution 3

Use the String.Split method to split by "blank space". More details here:

http://msdn.microsoft.com/en-us/library/system.string.split.aspx

If character by character then write your own function to do that.

Try this code:

Dim input As String = "characters"
Dim substrings() As String = Regex.Split(input, "")
Console.Write("{")
For ctr As Integer = 0 to substrings.Length - 1
   Console.Write("'{0}'", substrings(ctr))
   If ctr < substrings.Length - 1 Then Console.Write(", ")
Next
Console.WriteLine("}")
' The example produces the following output:   
'    {'', 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's', ''}

Using Regex, http://msdn.microsoft.com/en-us/library/8yttk7sy.aspx#Y2166.

Solution 4

Can you just put that one string in to an array? My VB is rusty, but try this:

Dim arr(0) As String
arr(0) = str

func(arr)

Solution 5

I'm not a VB expert, but this looks like the cleanest way to me:

func(New String() { str })

However, if that's not clean enough for you, you could use extension methods either specific to string:

func(str.ToStringArray)

or in a generic way:

func(str.ToSingleElementArray)

Here's the latter as an extension method:

<Extension> _
Public Shared Function ToSingleElementArray(Of T)(ByVal item As T) As T()
    Return New T() { item }
End Function
Share:
22,705
Yugal Jindle
Author by

Yugal Jindle

Everybody is a genius. But if you judge a fish by its ability to climb a tree, it will live its whole life believing that it is stupid. -- Anonymous Github : YugalJindle Twitter : @YugalJindle Google+ : +YugalJindle LinkedIn : http://www.linkedin.com/in/YugalJindle

Updated on April 02, 2020

Comments

  • Yugal Jindle
    Yugal Jindle about 4 years

    Well, I have a function that takes a string array as input...

    I have a string to process from that function...

    So,

    Dim str As String = "this is a string"
    
    func(// How to pass str ?)
    
    Public Function func(ByVal arr() As String)
         // Processes the array here
    End Function
    

    I have also tried:

    func(str.ToArray)  // Gives error since it converts str to char array instead of String array.
    

    How can I fix this?