从字符串中的每个单词获取第一个char的最短方法

Jav*_*ram 7 c# string split

我想要一个最短的方法来获得C#中字符串中每个单词的第一个字符.

我所做的是:

string str = "This is my style";
string [] output = str.Split(' ');
foreach(string s in output)
{
   Console.Write(s[0]+" ");
}

// Output
T i m s
Run Code Online (Sandbox Code Playgroud)

我想以最短的方式显示相同的输出...

谢谢

Che*_*hen 18

var firstChars = str.Split(' ').Select(s => s[0]);
Run Code Online (Sandbox Code Playgroud)

如果表现至关重要:

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

第二种解决方案可读性较差,但循环一次.

  • 使用`.Split("",StringSplitOptions.RemoveEmptyEntries)`来避免多个空格的错误. (3认同)

Ker*_*own 12

string str = "This is my style"; 
str.Split(' ').ToList().ForEach(i => Console.Write(i[0] + " "));
Run Code Online (Sandbox Code Playgroud)

  • 使用 `Array.ForEach(str.Split(' '), s => Console.Write(s[0] + " "));` 会更短更快。您可能还想使用 `StringSplitOptions.RemoveEmptyEntries` 来处理字符串以空格开头或包含连续空格的情况。 (4认同)

小智 6

打印字符串中每个单词的第一个字母

string SampleText = "Stack Overflow Com";
string ShortName = "";
SystemName.Split(' ').ToList().ForEach(i => ShortName += i[0].ToString());  
Run Code Online (Sandbox Code Playgroud)

输出:

SOC
Run Code Online (Sandbox Code Playgroud)