例如,我有一个字符串:
string s = "Alex Amonov,Semen Polov,John S,Alex Solid";
我需要显示:如果名字相同,则第二个名称会删除所有元素,除了第一个名称。
Alex A , Semen , John , Alex S
我该怎么做?
答案 0 :(得分:-1)
要根据您定义的规则实现输出,您可以使用:
var s = "Alex Amonov,Semen Polov,John S,Alex Solid";
var result = "";
foreach (var name in Regex.Split(s, ",").Where(x => !string.IsNullOrEmpty(x)))
{
var index = name.IndexOf(" ", StringComparison.InvariantCulture);
result += name[0] == name[index + 1]
? name.Substring(0, index) + " " + name[0] + ", "
: name.Substring(0, index) + ", ";
}
但请注意,它会产生
Alex A,Semen,John,Alex
答案 1 :(得分:-1)
这是考虑生成该输出的算法的一种方法:
,
)上拆分数组以生成名称列表这个过程可以使用LINQ进行拆分和分组,然后使用临时数组循环以按原始顺序存储最终结果,如下所示:
string s = "Alex Amonov,Semen Polov,John S,Alex Solid";
// split original list into separate names
var names = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
// split names into first-last pairs, and group by matching first names groups,
// preserving information about original order/index
var nameGroups = names.Select((n, i) => Tuple.Create(i, n.Split(' '))).GroupBy(n => n.Item2[0]).ToList();
// prepare output array to store final names in original order
var result = new string[names.Length];
foreach (var nameGroup in nameGroups)
{
// if only one matching first name in group, output just the first name
if (nameGroup.Count() == 1)
{
result[nameGroup.Single().Item1] = nameGroup.Single().Item2[0];
}
else
{
// if multiple matching names, include first letter of last name
foreach (var entry in nameGroup)
{
result[entry.Item1] = entry.Item2[0] + " " + entry.Item2[1][0];
}
}
}
// generate output comma-separated list of final output names in original order
var output = string.Join(" , ", result);
Console.WriteLine(output); // Alex A , Semen , John , Alex S
@Kaz在评论中指出,这个解决方案显然存在缺陷。如果两个名称的姓氏最初相同,则它们在输出中仍然是重复的。在这种情况下,我认为可以修改它以输出完整的姓氏。