2011-07-29 33 views
3

嗯,我有一个函数,采用一个字符串数组作为输入...如何将字符串转换为VB.NET中的字符串数组?

我有一个字符串,以从该函数处理...

所以,

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 

我也试过:

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

我该如何解决这个问题?

+0

你想如何将它变成一个数组?用空格分隔? – Jodaka

+0

没有..没有像这样..只需将“mystring”转换为一个数组与单个元素“mystring”。 –

回答

5

随着VB10,你可以简单地这样做:

func({str}) 

与旧版本你就必须做到:

func(New String() {str}) 
3

使用String.Split方法按“空格”拆分。更多细节在这里:

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

如果逐个字符然后写自己的函数来做到这一点。

试试这个代码:

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', ''} 

使用正则表达式,http://msdn.microsoft.com/en-us/library/8yttk7sy.aspx#Y2166

+0

不..我不希望我的字符串分裂! –

+1

所以,我误解你的问题...... :( –

5

只是实例化一个新的数组只包括你的字符串

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 
+0

那工程..**但是我们可以以一种更简洁的方式来做到这一点..?** 更直观的东西,比如'str.ToStringArray'什么的? –

+2

你正试图创建一个新类型的对象(在这种情况下是String())而不是你所拥有的一个。既然没有内置的方式,那么是否会采取一种“整洁”的方式?你总是可以写一个扩展方法来做到这一点。 – Jimmy

+1

@Yugal元骑士的[答案](http://stackoverflow.com/questions/6868885/how-to-convert-string-to-string-array-in-vb-net/6874143#6874143)是最好的事情我能想象。只需添加两个大括号'打印({s})' – MarkJ

2

可你只要把在一个数组一个字符串?我的VB是生锈,但试试这个:

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

func(arr) 
1

我不是一个VB的专家,但是这看起来像最清晰的方式对我说:

func(New String() { str }) 

然而,如果这还不够干净你,你可以使用扩展方法要么特定字符串:

func(str.ToStringArray) 

在一个通用的方式

func(str.ToSingleElementArray) 

这里是后者作为扩展方法:

<Extension> _ 
Public Shared Function ToSingleElementArray(Of T)(ByVal item As T) As T() 
    Return New T() { item } 
End Function 
+0

最清洁的方式是[func({str})',如[Meta-Knight的答案](http://stackoverflow.com/questions/6868885/how-to-convert-string-to-string-array-in- VB-净/ 6874143#6874143) – MarkJ

相关问题