2015-02-07 129 views
0

我試圖以我自己的形式爲每個商店創建唯一的代碼。我有兩個TextBox控件(TBNameStoreTBCodeStore)。我想要的是,當我寫商店的名稱,例如「兄弟在手臂」,在TBNameStore,然後TBCodeStore應該自動填充文本「BIA」識別TextBox中每個單詞的第一個字母

我該怎麼做?

+0

看空間和子串函數的'split'函數 – 2015-02-07 12:38:13

+0

請花點時間仔細閱讀* * [問] – Plutonix 2015-02-07 13:08:35

+0

@pasty現在我沒有任何關於我的情況的線索..現在iam試圖學習關於拆分和子串功能..就像Giorgi Nakeuri說的那樣.. – CrazyThink 2015-02-07 13:10:47

回答

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

@Bjørn-RogerKringsjå??,我的答案沒有錯誤... – 2015-02-07 13:42:27

+1

您的代碼工作正常,沒有錯誤,並容易理解我..謝謝..你已經節省了我的時間..:D – CrazyThink 2015-02-08 07:46:13

+1

@GreenFire完美!請注意,我的目的不是欺負你,而是讓你提高你的答案。另外請注意,您不必包含選項strict語句,因爲通過查看代碼很容易瞭解此選項是關閉/開啓的。 – 2015-02-08 16:08:19

0
使用上述 SplitSubString方法和 LINQ可能看起來像這樣

一種可能的解決方案:

  • 創建StringBuilder,其中每個字的每一個字符存儲
  • 分開使用指定的分隔符的話(默認爲空格)使用String.Split方法
  • 將數組轉換爲列表以應用LINQ-ToList擴展名=>ToList()
  • for each found => ForEach(sub(word as String)...
  • 從單詞中取第一個字符,將其轉換爲大寫並放入結果中 => result.Append(word。 SubString(0,1)。 ToUpper()
  • 返回其結果作爲字符串=> result.ToString()

的代碼看起來是這樣的:

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 
相關問題