Search This Blog

Friday, April 5, 2013

C# Code To Split String By Using Tabs As Delimmiter

We save some files as Tab delimited. In MS-Excel also have option to save the file as Tab delimited file. In that file there is a tab between each cells. We can read cell by cell using the following sample code.

Following Code snippet will split string using tab and store it in to a ArrayList.

public static void SplitTabs(string strText, ArrayList ArrTabs)
{

    int nStart = 0;
    int nPos = -1;
    int nLength = 0;
 //   strText = strText.Trim();
    nPos = strText.IndexOf("\t");
    if (nPos == -1 && strText.Length > 0)
    {
        ArrTabs.Add(strText);
    }
    while (nPos > -1)
    {
        nLength = nPos - nStart;
        string strLine = strText.Substring(nStart, nLength);
        strLine = strLine.Trim();

    //    if (strLine.Length > 0)
        {
            ArrTabs.Add(strLine);
        }
        nStart = nPos;
        nPos = strText.IndexOf("\t", nPos + 1);
        if (nPos == -1 && strText.Length > (nStart + 1)) //Last and remaining Text
        {
            strLine=strText.Substring(nStart );
            strLine = strLine.Trim();
            if (strLine.Length > 0)
            {
                ArrTabs.Add(strLine);
            }
        }
        nStart ++;

    }
}
Usage:
string strTxt = "'abc'\t'bcd'\t'xyz'";
ArrayList ArrLines= new ArrayList();
SplitTabs(strTxt, ArrLines);
 foreach (string str in ArrLines)
 {
      Console.WriteLine(str);
 }

Output:


No comments:

Post a Comment