就在我编写自己的函数之前,只想检查是否存在类似 string.split(string input, params int[] indexes) .NET库的函数?此函数应该将字符串拆分为传递给它的索引.
编辑:我不应该添加string.join句子 - 这是令人困惑的.
Pau*_*ane 14
您可以使用String实例方法Substring.
string a = input.Substring(0, 10);
string b = input.Substring(10, 5);
string c = input.Substring(15, 3);
Run Code Online (Sandbox Code Playgroud)
所有其他答案似乎太复杂了,所以我采取了一个刺.
using System.Linq;
public static class StringExtensions
{
/// <summary>
/// Returns a string array that contains the substrings in this instance that are delimited by specified indexes.
/// </summary>
/// <param name="source">The original string.</param>
/// <param name="index">An index that delimits the substrings in this string.</param>
/// <returns>An array whose elements contain the substrings in this instance that are delimited by one or more indexes.</returns>
/// <exception cref="ArgumentNullException"><paramref name="index" /> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">An <paramref name="index" /> is less than zero or greater than the length of this instance.</exception>
public static string[] SplitAt(this string source, params int[] index)
{
index = index.Distinct().OrderBy(x => x).ToArray();
string[] output = new string[index.Length + 1];
int pos = 0;
for (int i = 0; i < index.Length; pos = index[i++])
output[i] = source.Substring(pos, index[i] - pos);
output[index.Length] = source.Substring(pos);
return output;
}
}
Run Code Online (Sandbox Code Playgroud)