字符串由index/params分割?

max*_*axp 8 c# string split

就在我编写自己的函数之前,只想检查是否存在类似 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)

  • 他仍然需要进行多次方法调用; 我认为他正在寻找那种*精确的*方法(虽然我很确定这*是*他将如何实现它.因为他必须这样做.) (2认同)

roy*_*key 7

所有其他答案似乎太复杂了,所以我采取了一个刺.

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)

  • 埋葬例外会破坏惯例。使用字符串时,c#中的约定是在索引超出范围时引发错误。而且,由于这是一种实用程序和重用方法,因此我选择为这些异常添加文档。 (2认同)

hav*_*dhu 5

Split 方法根据识别模式分割字符串。非常适合分解逗号分隔的列表等。

但你是对的,没有内置的字符串方法来实现你想要的。