Search This Blog

Friday, April 5, 2013

C# Code to Split String Into Lines

In parsing some times we need to get the string line by line. We can split the line by line using the end of line character('\r\n'). We need to find its position and it can be splited suing sub-string functions and given below.

Following code snippet split the string in to lines and store it in a Array list.
public static void SplitLines(string strText, ArrayList ArrLines)
{
    int nStart = 0;
    int nPos = -1;
    int nLength = 0;
    char[] szTrim = { '\r', '\n' };
    strText = strText.Trim(szTrim);
    nPos = strText.IndexOf("\r\n");
    if (nPos == -1 && strText.Length > 0)
    {
        ArrLines.Add(strText);
    }
    while (nPos > -1)
    {
        nLength = nPos - nStart;
        string strLine = strText.Substring(nStart, nLength);
        strLine = strLine.Trim(szTrim);

        if (strLine.Length > 0)
        {
            ArrLines.Add(strLine);
        }
        nStart = nPos;
        nPos = strText.IndexOf("\r\n", nPos + 1);

        if (nPos == -1 && strText.Length > (nStart + 1)) //Last and remaining Text
        {
            strLine = strText.Substring(nStart);
            strLine = strLine.Trim(szTrim);

            if (strLine.Length > 0)
            {
                ArrLines.Add(strLine);
            }
        }

        nStart++;

    }
}
 
Usage:
 string strTxt = "abc \r\nbcd \r\nxyz";
 ArrayList ArrLines= new ArrayList();
 SplitLines(strTxt,ArrLines);


 
//To print result
 foreach (string str in ArrLines)
 {
    Console.WriteLine(str);
 } 


Output screenshot:
 
 

No comments:

Post a Comment