shortest way to get first char from every word in a string

前端 未结 5 850
感情败类
感情败类 2021-01-12 05:40

I want a shortest way to get 1st char of every word in a string in C#.

what I have done is:

string str = \"This is my style\";
string [] output = str         


        
5条回答
  •  孤独总比滥情好
    2021-01-12 06:27

    var firstChars = str.Split(' ').Select(s => s[0]);
    

    If the performance is critical:

    var firstChars = str.Where((ch, index) => ch != ' ' 
                           && (index == 0 || str[index - 1] == ' '));
    

    The second solution is less readable, but loop the string once.

提交回复
热议问题