使用LINQ从C#中的字符串获取首字母缩写词? [英] Get an acronym from a string in C# using LINQ?

查看:173
本文介绍了使用LINQ从C#中的字符串获取首字母缩写词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我编写Java风格的缩写的函数的方法:

Here is how I would write a function to make an acronym in Java style:

    string makeAcronym(string str)
    {
        string result = "";
        for (int i = 0; i < str.Length; i++)
        {
            if (i == 0 && str[i].ToString() != " ")
            {
                result += str[i];
                continue;
            }

            if (str[i - 1].ToString() == " " && str[i].ToString() != " ")
            {
                result += str[i];
            }
        }

        return result;
    }

是否可以使用LINQ或使用一些内置的C#函数来实现更优雅的方式?

Is there a more elegant way I can do it with LINQ, or using some built in C# function?

推荐答案

以下是几个选项

使用字符串的.NET 4唯一选项.加入:

A .NET 4 only option using string.Join:

 string acronym = string.Join(string.Empty,
      input.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).Select(s => s[0])
      );

在.NET 3.5(或4.0)中,您可以执行以下操作:

In .NET 3.5 (or 4.0), you can do:

 string acronym = new string(input.Split(new[] {' '}, 
      stringSplitOptions.RemoveEmptyEntries).Select(s => s[0]).ToArray());

另一个选择(我个人选择),根据您的原始逻辑:

Another option (my personal choice), based on your original logic:

 string acronym = new string(
      input.Where( (c,i) => c != ' ' && (i == 0 || input[i-1] == ' ') )
      .ToArray()
    );

这篇关于使用LINQ从C#中的字符串获取首字母缩写词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆