How to extract first letters from different words

2019-09-27 15:49发布

I want to extract first letter of each word in a string. I have done a lot of googling and still without any aid.
For example,string text = "I Hate Programming";
The desired answer should be like:

IHP

I know you guys are very good, I'm just new. thanks.

3条回答
相关推荐>>
2楼-- · 2019-09-27 16:02

If you know that your delimiter is a space, you can do the following.

string text = "my text here";
string firstLetters = "";

foreach(var part in text.split(' ')){
    firstLetters += part.substring(0,1);
}

Basically you split your string by the space character, and grab the first letter using substring of each word.

查看更多
趁早两清
3楼-- · 2019-09-27 16:11

With a little bit of LINQ:

string text = "I Hate Programming";
string firstLetters = 
    String.Join(String.Empty, text.Split(new[] {' '}).Select(word => word.First())) 

If you want to include characters likes - and ' as the start of words, just add them to the list of characters in the call to Split().

查看更多
等我变得足够好
4楼-- · 2019-09-27 16:20
var str = "Dont Hate Programming :D"
var firstLetters = new String(str.Split(' ').Select(x => x[0]).ToArray());
Console.WriteLine(firstLetters); // DHP:
查看更多
登录 后发表回答