Split text into substrings seperated more than one character

serkan sendur 0 Tallied Votes 161 Views Share

Enables creating substring arrays from strings seperated by character sets .

In c# there is a built-in split method  with which you can create a substring  array seperated by one character  from a string as follows : 

// string seperated by colons ';'
    string info = "mark;smith;123 csharp drive;toronto;canada";

    string[] arInfo = new string[4];
    
    // define which character is seperating fields
    char[] splitter  = {';'};
            
    arInfo = info.Split(splitter);

    for(int x = 0; x < arInfo.Length; x++)
    {
        Response.Write(arInfo[x] + "<br>");
    }

but what if i want to create a substring array seperated by more than one characters like '#$' or '#$%'  ? 

The following method does exactly what i mean :

public string[] SplitText(string textToSplit,string splitter)
    {
        if (textToSplit.IndexOf(splitter) != -1 && splitter != string.Empty)
        {
            int count = 0;
            string temp = textToSplit;
            int count2 = splitter.Length;
            while (temp.IndexOf(splitter) != -1)
            {
                int seq = temp.IndexOf(splitter);
                int top = seq + count2;
                temp = temp.Remove(0, top);
                count++;

            }
            string[] splittedText = new string[count + 1];

            int i = 0;
            while (textToSplit.IndexOf(splitter) != -1)
            {
                int seq = textToSplit.IndexOf(splitter);
                splittedText[i] = textToSplit.Substring(0, seq);
                textToSplit = textToSplit.Remove(0, (seq + count2));
                i++;
            }
            splittedText[count] = textToSplit;
            return splittedText;
        }
        return new string[] {textToSplit};
       
    }
kathirvelmm 0 Newbie Poster

Good for single splitter the coding is quiet easy.
Which could be used for multiple characters with a single "String.replace" operation

string info = "mark\nsmith\n123 csharp drive\ntoronto\ncanada";
string mystring = info.Replace("\n", ";");

output:

mark;smith;123 csharp drive;toronto;canada

which could be used with simple splitter coding

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.