开发者

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

Well, I have a fun开发者_运维百科ction 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?


With VB10, you can simply do this:

func({str})

With an older version you'll have to do:

func(New String() {str})


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


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.


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)


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


You mean like String.ToCharArray? Also, you can access the chars contained in the string directly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜