我有以下格式的string

string instance = "{112,This is the first day 23/12/2009},{132,This is the second day 24/12/2009}"

private void parsestring(string input)
{
    string[] tokens = input.Split(','); // I thought this would split on the , seperating the {}
    foreach (string item in tokens)     // but that doesn't seem to be what it is doing
    {
       Console.WriteLine(item);
    }
}

我想要的输出应如下所示:
112,This is the first day 23/12/2009
132,This is the second day 24/12/2009

但是目前,我得到以下一个:
{112
This is the first day 23/12/2009
{132
This is the second day 24/12/2009

我是C#的新手,任何帮助将不胜感激。

最佳答案

好吧,如果您有一个称为ParseString的方法,那么它返回一些东西是一件好事(而说它是ParseTokens可能不是一件坏事)。因此,如果执行此操作,则可以转到以下代码

private static IEnumerable<string> ParseTokens(string input)
{
    return input
        // removes the leading {
        .TrimStart('{')
        // removes the trailing }
        .TrimEnd('}')
        // splits on the different token in the middle
        .Split( new string[] { "},{" }, StringSplitOptions.None );
}

之所以对您不起作用,是因为您对split方法的工作方式的理解是错误的,它将有效地拆分示例中的所有,

现在,如果将所有这些放在一起,您会在dotnetfiddle中得到类似的信息
using System;
using System.Collections.Generic;

public class Program
{
    private static IEnumerable<string> ParseTokens(string input)
    {
        return input
            // removes the leading {
            .TrimStart('{')
            // removes the trailing }
            .TrimEnd('}')
            // splits on the different token in the middle
            .Split( new string[] { "},{" }, StringSplitOptions.None );
    }

    public static void Main()
    {
        var instance = "{112,This is the first day 23/12/2009},{132,This is the second day 24/12/2009}";
        foreach (var item in ParseTokens( instance ) ) {
            Console.WriteLine( item );
        }
    }
}

关于c# - 有效地分割为 "{ {}, {}, ...}"格式的字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58123401/

10-12 20:25