How to extract first letters from different words in a string in c# [closed]

混江龙づ霸主 提交于 2019-12-13 09:55:57

问题


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:


来源:https://stackoverflow.com/questions/16368182/how-to-extract-first-letters-from-different-words-in-a-string-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!