vb.net 简单地从字符串中获取首字母 - Visual Basic
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13177664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple get initials from string - Visual Basic
提问by Ds.109
Simple beginner exercise:
简单的初学者练习:
There's an input box where you put in your name seperated by spaces, then get the first letter from the first and last name and out put it to a label
有一个输入框,你把你的名字用空格隔开,然后从名字和姓氏中取出第一个字母,然后把它放到一个标签上
I.e (Joe Bob) = JB
即(乔鲍勃)= JB
I know this could be done with an array, but the exercise is more to using string functions like substring, IndexOf, Remove, Replace etc...
我知道这可以用数组来完成,但练习更多的是使用字符串函数,如 substring、IndexOf、Remove、Replace 等......
采纳答案by Mark Hall
回答by Olivier Jacot-Descombes
There is the handy string method Splitwhich splits a string at whitespaces by default, if you don't specify another delimiter.
Split如果您不指定另一个分隔符,则有一个方便的字符串方法,它默认在空格处拆分字符串。
Dim words As String() = TextBox1.Text.Split()
Dim initials As String = ""
For Each word As String In words
initials &= word(0)
Next
Note: Strings can be indexed as if they were Chararrays. word(0)is the first character of word.
注意:字符串可以像Char数组一样被索引。word(0)是 的第一个字符word。
initials &= word(0)
is shorthand for
是简写
initials = initials & word(0)
回答by Nianios
You can try this:
你可以试试这个:
dim str as String=TextBox1.Text
Label1.Text=str.Remove(1, str.LastIndexOf(" ")).Remove(2)
If you want, you can do it in one line:
如果你愿意,你可以在一行中完成:
Label1.Text = TextBox1.Text.Remove(1, TextBox1.Text.LastIndexOf(" ")).Remove(2)
回答by Ric
Could try something like this too!
也可以试试这样的!
Dim str As String = textBox1.Text
Dim initials As String = New String(str.Split(" "c).Select(Function(f) f(0)).ToArray)

