在c#中拆分字符串

时间:2017-07-21 13:21:45

标签: c# asp.net string

我有一个字符串,格式如" 945-20-4:397-3:320"或" 945-20-41-90-4:397-3:320" 。我需要将它分为第一个":"最后" - "从第1"左边开始:"。

喜欢" 945-20-4:397-3:320"我需要2部分,比如' 945-20' &安培; ' 4:397-3:320'

对于" 945-20-41-90-4:37-3:320-1:232",2部分将类似于' 945-20-41-90'和' 4:37-3:320-1:232'。

如何洒了?

1 个答案:

答案 0 :(得分:0)

这里你去3:D

void Main()
{
    Splitter.Print(Splitter.GetParts("945-20-4:397-3:320"));
    Splitter.Print(Splitter.GetParts("945-20-41-90-4:397-3:320"));
}

unsafe static class Splitter
{
    public static ValueTuple<string, string> GetParts(string whole)
    {
        var builder = new StringBuilder();

        fixed (char* parts = whole)
        {
            char* lastDashPosition = null;
            var terminus = parts + whole.Length;
            for (var x = parts; x < terminus; ++x)
            {
                switch (*x)
                {
                    case ':':
                        builder.Remove((int)(lastDashPosition  - parts), 
                            (int)(x - lastDashPosition));
                        return ValueTuple.Create(builder.ToString(), 
                            whole.Substring((int)(lastDashPosition + 1 - parts)));
                    case '-':
                        lastDashPosition = x;
                        break;
                }

                builder.Append(*x);
            }

            throw new InvalidOperationException("String not in expected format.");
        }
    }

    public static void Print(ValueTuple<string, string> v) 
    {
        Debug.Print("Token 1: " + v.Item1);
        Debug.Print("Token 2: " + v.Item2);
    }
}