Reputation: 45646
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?
Upvotes: 5
Views: 24709
Reputation: 2789
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.
Upvotes: 3
Reputation: 17845
With VB10, you can simply do this:
func({str})
With an older version you'll have to do:
func(New String() {str})
Upvotes: 8
Reputation: 1499810
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
Upvotes: 1
Reputation: 163
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)
Upvotes: 2
Reputation: 28376
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
Upvotes: 5
Reputation: 4005
You mean like String.ToCharArray? Also, you can access the chars contained in the string directly.
Upvotes: -1