Separated string splitting 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 separator was used between each section? I am trying to recreate the string as a whole.

+5
source share
3 answers

As @ Davy8 noted, there is no built-in way. Here is a VERY simple example for you to start writing your own 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; }
}
+3
source

There is no built-in way that I know of. You might be better off writing your own custom separation method that tracks delimiters.

+2
source

. , , "h" "o"?

, :

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

?

+1

All Articles