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

前端 未结 5 853
感情败类
感情败类 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:09

    I think your solution is perfectly fine, but if you want better performance you can try:

    string str = "This is my style";
    Console.Write(str[0]);
    for(int i = 1; i < str.Length; i++)
    {
        if(str[i-1] = " ")
            Console.Write(" " + str[i]);
    }
    

    You might get a lower constant factor with this code but it still runs in O(n). Also, I assume that there will never be more than one space in a row and it won't start with space.

    If you want to write less code you can try:

    str result = str.Split(" ").Select(y => y[0]).ToList();
    

    Or something.

提交回复
热议问题