gpt4 book ai didi

c# - 使用 LINQ 从 C# 中的字符串获取首字母缩略词?

转载 作者:太空狗 更新时间:2023-10-29 19:49:21 24 4
gpt4 key购买 nike

下面是我将如何编写一个函数来制作 Java 风格的首字母缩略词:

    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# 函数来实现?

最佳答案

这里有几个选项

使用 string.Join 的仅 .NET 4 选项:

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

在 .NET 3.5(或 4.0)中,您可以:

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

另一种选择(我个人的选择),基于你原来的逻辑:

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

关于c# - 使用 LINQ 从 C# 中的字符串获取首字母缩略词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4000304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com