嗨,我有一個代碼可以使用 for 回圈轉換 String 陣列的每個元素的小寫字母。問題是只有最后一個元素出現在輸出(標簽)上,但在除錯輸出上顯示良好
Dim lst() = {"apple", "banana", "cherry"}
For Each item As String In lst
Dim array() As Char = item.ToCharArray
array(0) = Char.ToUpper(array(0))
Dim newS = New String(array)
Dim value As String = String.Join("/", newS)
TextBox1.Text = value
Debug.Write(value)
Output.Text = value
Next
Debug.WriteLine("")
這是發生的問題,它將標簽更改為帶有大寫字母的最后一個元素,因為它應該是,但我希望輸出與除錯輸出相同
蘋果香蕉櫻桃
uj5u.com熱心網友回復:
您不需要顯式定義Char陣列。一個字串有一個Char(index)屬性,它是Default屬性。我們可以直接在字串上使用它。MyString(index)
我們將方法String回傳的 new 分配給Replace陣列的一個元素。index從0Integer 的默認值開始,并在For Each回圈的每次迭代中遞增。
最后,在 之后For Each,我們將 分配Join給標簽。
您的代碼以及哪里出錯了。
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim lst() = {"apple", "banana", "cherry"}
For Each item As String In lst
Dim array() As Char = item.ToCharArray
array(0) = Char.ToUpper(array(0))
Dim newS = New String(array)
Dim value As String = String.Join("/", newS)
TextBox1.Text = value 'Overwrites the last value you assigned to the Text property
Debug.Write(value) 'Adds on to the last value it wrote in the debug window.
Label1.Text = value 'Overwrites the last value you assigned to the Text property
Next
Debug.WriteLine("")
End Sub
更正的代碼。
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim lst = {"apple", "banana", "cherry"}
Dim index As Integer
For Each item As String In lst
lst(index) = item.Replace(item(0), Char.ToUpper(item(0)))
index = 1
Next
Label1.Text = String.Join("", lst)
End Sub
這是 WinForms 但您關心的代碼應該沒有任何不同,只是事件程序格式。
uj5u.com熱心網友回復:
您甚至可以在沒有顯式回圈的情況下將其放在一行中。
Dim lst = {"apple", "banana", "cherry"}
Output.Text = String.Join("", lst.Select(Function(x) CultureInfo.CurrentCulture.TextInfo.ToTitleCase(x))))
雖然它看起來非常“聰明”,但有幾件事需要考慮。
如果原始串列非常大(意味著數千個字串),這會降低效率,因為 Linq Select 和隨后的 Join 將創建一個新串列,使使用的記憶體增加一倍。
如果要更改第一個字符以上,則 ToTitleCase 方法不起作用
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/343693.html
