请考虑以下代码:
string[] s = new[] { "Rob", "Jane", "Freddy" }; string joined = string.Join(", ", s); // joined equals "Rob, Jane, Freddy"
出于UI原因,我可能希望显示字符串"Rob, Jane or Freddy"
.
有关最简洁的方法的任何建议吗?
我正在寻找一些简洁的东西.由于我只连接少量(<10)字符串,所以我不担心这里的运行时性能.
简明扼要的意思?还是跑?最快的运行将是手摇StringBuilder
.但要键入,可能(编辑句柄0/1等):
string joined; switch (s.Length) { case 0: joined = ""; break; case 1: joined = s[0]; break; default: joined = string.Join(", ", s, 0, s.Length - 1) + " or " + s[s.Length - 1]; break; }
该StringBuilder
方法可能类似于:
static string JoinOr(string[] values) { switch (values.Length) { case 0: return ""; case 1: return values[0]; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < values.Length - 2; i++) { sb.Append(values[i]).Append(", "); } return sb.Append(values[values.Length-2]).Append(" or ") .Append(values[values.Length-1]).ToString(); }
连接除最后一个之外的所有内容.手动完成最后一个.
在string []上创建一个扩展方法,它实现与string.Join相同的逻辑,但最后一项将附加"或".
string[] s = new[] { "Rob", "Jane", "Freddy" }; Console.WriteLine(s.BetterJoin(", ", " or "));
// --- 8 <----
namespace ExtensionMethods { public static class MyExtensions { public static string BetterJoin(this string[] items, string separator, string lastSeparator) { StringBuilder sb = new StringBuilder(); int length = items.Length - 2; int i = 0; while (i < length) { sb.AppendFormat("{0}{1}", items[i++], separator); } sb.AppendFormat("{0}{1}", items[i++], lastSeparator); sb.AppendFormat("{0}", items[i]); return sb.ToString(); } } }