How to extract first letters from different words

2019-09-27 15:44发布

问题:

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.

回答1:

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.



回答2:

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().



回答3:

var str = "Dont Hate Programming :D"
var firstLetters = new String(str.Split(' ').Select(x => x[0]).ToArray());
Console.WriteLine(firstLetters); // DHP: