我很想弄清楚如何制作一个程序来改变数组中名称的顺序。 它期望程序首先显示姓氏,并在名字后面显示名称的其余部分。
static void Main(string[] args)
{
string[] names = { "Paul Page Load Wood", "Michael Kraiser Unter", "Mia Rock Spark" };
/*Present the names
names[1] = "Wood, Paul P. l.";
names[2] = "Unter, Michael K.";
names[3] = "Spark, Mia R."*/
}
你能帮忙吗?
谢谢
这是我到目前为止所拥有的:
static void Main(string[] args)
{
string[] names = { "Paul Page Load Wood", "Michael Kraiser Unter", "Mia Rock Spark" };
int i = 0;
foreach (string name in names)
{
string[] eachName = name.Split(' '); // I was advised to no use .split
for (int j = 0; j < eachName.Length; j++)
{
Console.WriteLine("{0} {1}", j, eachName[j]);
}
i++;
Console.WriteLine();
}
}
答案 0 :(得分:1)
首先,让详细说明:
"John" -> "John"
(什么都不做)"John Smith" -> "Smith, John"
(最后,第一个)"John Peter Jack Smith" -> "Smith, John P. J."
(最后,第一个,其他按顺序为单个字母)有了这些规则,我们可以实现简单的重新排序:
private static String ReOrderNamesParts(string name) {
if (string.IsNullOrEmpty(name))
return name;
string[] parts = name.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length <= 0)
return name;
StringBuilder sb = new StringBuilder(parts[parts.Length - 1]);
if (parts.Length > 2) {
sb.Append(", ");
sb.Append(parts[0]);
}
for (int i = 1; i < parts.Length - 1; ++i) {
sb.Append(' ');
sb.Append(parts[i].Substring(0, 1));
sb.Append('.');
}
return sb.ToString();
}
所以你可以把
string[] names = { "Paul Page Load Wood", "Michael Kraiser Unter", "Mia Rock Spark" };
for (int i = 0; i < names.Length; ++i)
names[i] = ReOrderNamesParts(names[i]);
或者如果您只想打印出来:
Console.Write(String.Join(Environment.NewLine,
names.Select(name => eOrderNamesParts(names))));