我尝试以我制作的形式为每个商店创建一个唯一的代码。我有两个TextBox控件(TBNameStore
和TBCodeStore
)。我想要的是,当我在TBNameStore
中写下商店名称时,例如" Brothers in Arm" ,然后TBCodeStore
应自动成为填写了文本" BIA" 。
我该怎么做?
答案 0 :(得分:3)
我写的代码可以帮助您解决问题。
Option Strict On
Public Class Form1
Public Function GetInitials(ByVal MyText As String) As String
Dim Initials As String = ""
Dim AllWords() As String = MyText.Split(" "c)
For Each Word As String In AllWords
If Word.Length > 0 Then
Initials = Initials & Word.Chars(0).ToString.ToUpper
End If
Next
Return Initials
End Function
Private Sub TBNameStore_TextChanged(sender As Object, e As EventArgs) Handles TBNameStore.TextChanged
TBCodeStore.Text = GetInitials(TBNameStore.Text)
End Sub
End Class
就像你看到的那样,GetInitials会为你提供文本中所有单词的第一个字母。
答案 1 :(得分:0)
使用上述Split
和SubString
方法以及LINQ的一种可能解决方案可能如下所示:
代码如下所示:
private function abbreviation(input as String, optional delimiter as String = " ")
dim result = new StringBuilder()
input.Split(delimiter) _
.ToList() _
.ForEach(sub (word as String)
result.Append(word.SubString(0, 1).ToUpper())
end sub)
return result.ToString()
end function
用法:
dim s = "Brothers in Arms"
Console.WriteLine("{0} => {1}", s, abbreviation(s))
,输出看起来像预期的那样:
Brothers in Arms => BIA