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

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

    Print first letter of each word in a string

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

    Output:

    SOC
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-12 06:15

    Regular expressions could be the answer:

      Regex.Matches(text, @"\b(\w{1})")
        .OfType<Match>()
        .Select(m => m.Groups[1].Value)
        .ToArray();
    
    0 讨论(0)
  • 2021-01-12 06:18
    string str = "This is my style"; 
    str.Split(' ').ToList().ForEach(i => Console.Write(i[0] + " "));
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题