这并不能直接回答 您的 笼统问题,而是在最有可能的常见情况下(或者至少在我遇到这个 SO 问题时我正在寻找答案的情况下) ) 其中indexes 是单个int,这种扩展方法比返回string[] 数组要干净一些,尤其是在C# 7 中。
为了它的价值,我使用string.Substring() 对创建两个char[] 数组、调用text.CopyTo() 并通过调用new string(charArray) 返回两个字符串进行了基准测试。使用 string.Substring() 的速度大约是原来的两倍。
C# 7 语法
jdoodle.com example
public static class StringExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static (string left, string right) SplitAt(this string text, int index) =>
(text.Substring(0, index), text.Substring(index));
}
public static class Program
{
public static void Main()
{
var (left, right) = "leftright".SplitAt(4);
Console.WriteLine(left);
Console.WriteLine(right);
}
}
C# 6 语法
jdoodle.com example
注意:在 C# 7 之前的版本中使用 Tuple<string, string> 并不会节省太多的冗长性,实际上只返回一个 string[2] 数组可能更简洁。
public static class StringExtensions
{
// I'd use one or the other of these methods, and whichever one you choose,
// rename it to SplitAt()
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Tuple<string, string> TupleSplitAt(this string text, int index) =>
Tuple.Create<string, string>(text.Substring(0, index), text.Substring(index));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string[] ArraySplitAt(this string text, int index) =>
new string[] { text.Substring(0, index), text.Substring(index) };
}
public static class Program
{
public static void Main()
{
Tuple<string, string> stringsTuple = "leftright".TupleSplitAt(4);
Console.WriteLine("Tuple method");
Console.WriteLine(stringsTuple.Item1);
Console.WriteLine(stringsTuple.Item2);
Console.WriteLine();
Console.WriteLine("Array method");
string[] stringsArray = "leftright".ArraySplitAt(4);
Console.WriteLine(stringsArray[0]);
Console.WriteLine(stringsArray[1]);
}
}