2015-02-07 124 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 
相关问题