簡體   English   中英

如何在VB.NET中將字符串轉換為字符串數組?

[英]How to convert string to string array in 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.

我怎樣才能解決這個問題?

使用VB10,您可以簡單地執行此操作:

func({str})

使用舊版本,您將不得不這樣做:

func(New String() {str})

只需實例化一個包含你的字符串的新數組

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

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

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

你能把這一個字符串放入一個數組嗎? 我的VB生銹了,但試試這個:

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

func(arr)

我不是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

你的意思是像String.ToCharArray 此外,您可以直接訪問字符串中包含的字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM