如何解决C#获取DisplayName的缩写
我正在尝试从显示名称中提取缩写,以用于显示其缩写。 我发现这很困难,因为字符串是一个包含一个或多个单词的值。我该如何实现?
示例:
'约翰·史密斯'=> JS
'史密斯,约翰'=> SJ
'约翰'=> J
'Smith'=> S
public static SearchDto ToSearchDto(this PersonBasicDto person)
{
return new SearchDto
{
Id = new Guid(person.Id),Label = person.DisplayName,Initials = //TODO: GetInitials Code
};
}
我使用以下解决方案:我创建了一个帮助程序方法,该方法可以测试多种情况。
public static string GetInitials(this string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return string.Empty;
}
string[] nameSplit = name.Trim().Split(new string[] { ","," " },StringSplitOptions.RemoveEmptyEntries);
var initials = nameSplit[0].Substring(0,1).ToUpper();
if (nameSplit.Length > 1)
{
initials += nameSplit[nameSplit.Length - 1].Substring(0,1).ToUpper();
}
return initials;
}
解决方法
以下内容如何:
void Main()
{
Console.WriteLine(GetInitials("John Smith"));
Console.WriteLine(GetInitials("Smith,John"));
Console.WriteLine(GetInitials("John"));
Console.WriteLine(GetInitials("Smith"));
}
private string GetInitials(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return string.Empty;
}
var splitted = name?.Split(' ');
var initials = $"{splitted[0][0]}{(splitted.Length > 1 ? splitted[splitted.Length - 1][0] : (char?)null)}";
return initials;
}
输出:
JS-SJ-J-S
,简单易懂的代码,并处理包含名字,中间名和姓氏的名称,例如“ John Smith William”。
Console.WriteLine(GetInitials("John Smith")); // JS
Console.WriteLine(GetInitials("Smith,John")); // SJ
Console.WriteLine(GetInitials("John")); // J
Console.WriteLine(GetInitials("Smith")); // S
Console.WriteLine(GetInitials("John Smith William")); // JSW
static string GetInitials(string name)
{
// StringSplitOptions.RemoveEmptyEntries excludes empty spaces returned by the Split method
string[] nameSplit = name.Split(new string[] { ","," "},StringSplitOptions.RemoveEmptyEntries);
string initials = "";
foreach (string item in nameSplit)
{
initials += item.Substring(0,1);
}
return initials;
}
,
或者只是另一种变体,作为扩展方法,只需进行少量的健全性检查
给予
public static class StringExtensions
{
public static string GetInitials(this string value)
=> string.Concat(value
.Split(new[] { ' ' },StringSplitOptions.RemoveEmptyEntries)
.Where(x => x.Length >= 1 && char.IsLetter(x[0]))
.Select(x => char.ToUpper(x[0])));
}
用法
var list = new List<string>()
{
"James blerg Smith","Michael Smith","Robert Smith 3rd","Maria splutnic Garcia","David Smith","Maria Rodriguez","Mary Smith","Maria Hernandez"
};
foreach (var name in list)
Console.WriteLine(name.GetInitials());
输出
JBS
MS
RS
MSG
DS
MR
MS
MH
,
下面的代码来自here。该代码的作用是从字符串中获取每个单词的第一个字母,并将其输出为大写字母。
static void printInitials(String name)
{
if (name.Length == 0)
return;
// Since touuper() returns int,// we do typecasting
Console.Write(Char.ToUpper(name[0]));
// Traverse rest of the string and
// print the characters after spaces.
for (int i = 1; i < name.Length - 1; i++)
if (name[i] == ' '&((i + 1)!=name.Length))
Console.Write(" " + Char.ToUpper(name[i + 1]));
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。