开发者

String split with delimiter in C#/ASP.Net

If I do this:

 string text = "Hello, how are you?";

 string[] split = text.Split('h', 'o');

How do I get a list of what delimiter was used between each split? I'm开发者_如何学运维 trying to recreate the string as a whole.


As @Davy8 mentioned, there is no built in way. Here's a VERY simple example to get you going on writing a custom method.

void Main()
{
    string text = "Hello, how are you?";
    List<SplitDefinition> splitDefinitionList = CustomSplit(text, new char[] { 'h', 'o' });
}

public List<SplitDefinition> CustomSplit(string source, char[] delimiters)
{
    List<SplitDefinition> splitDefinitionList = new List<SplitDefinition>();

    foreach(char d in delimiters)
    {
        SplitDefinition sd = new SplitDefinition(d, source.Split(d));           
        splitDefinitionList.Add(sd);
    }

    return splitDefinitionList;
}

public class SplitDefinition
{
    public SplitDefinition(char delimiter, string[] splits)
    {
        this.delimiter = delimiter;
        this.splits = splits;
    }

    public char delimiter { get; set; }
    public string[] splits { get; set; }
}


There isn't a built in way that I'm aware of. You're probably better off writing your own custom split method that keeps track of the delimiters.


This is impossible. The string has been split, so how can you possibly know if the split was based on a 'h' or an 'o'?

Anyways if you can do this:

 string[] split = text.Split('h', 'o');

then why not also store those characters?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜