c# Splitting Text String into max 40chrs rows

andrewmilner
andrewmilner used Ask the Experts™
on
I have a text box in a windows form application and I need to write the text to a text file but i need to split the text into either an array or table or something.  It's just one text box.  The text needs to be split/wrapped by a max of 40 characters per line.

Whats the best way to split the text with a for loop or something.  I would like the split to detect if there are extra paragraphs.  Would it be RegExp?

If there is an extra paragraph then ideally your code sample will account for this.

Hope you can help.
Thanks,
Andrew.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
leakim971Multitechnician
Top Expert 2014

Commented:
Hello andrewmilner

Have a look to this code :
 
            String s = "0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ0123456789ABCDEFGHIGEND";
            int l = 0;
            System.Collections.ArrayList t = new System.Collections.ArrayList();
            for(int i=0;i<s.Length;i+=40) {
                l = ((i + 40) < s.Length) ? 40 : (s.Length - i);
                t.Add(s.Substring(i,l));
            } 
            String[] sa = (string[])t.ToArray(typeof(string));

Open in new window

HainKurtSr. System Analyst

Commented:
this one is pretty close, just finds spaces now :)
    private String splitLines(String tInp, int n) {
        String ln = "", tOut = "";
        int x = 0, y = 0;
 
        while (x < tInp.Length)
        {
            if (x + n < tInp.Length)
                ln = tInp.Substring(x, n);
            else
                ln = tInp.Substring(x, tInp.Length - x);
 
            y = ln.LastIndexOf(" ");
            y = y > 0 ? y : ln.Length;
 
            ln = ln.Substring(0, y);
            tOut = tOut + (char)13 + ln;
            x = x + ln.Length;
        };
 
        return tOut;
    }
 
    protected void Page_Load(object sender, EventArgs e)
    {
        txtOut.Text = splitLines(txtInp.Text, 40);
    }

Open in new window

anarki_jimbelSenior Developer

Commented:
Try the following code. It's not thoroughly tested but it works and handles different situations.
        private List<string> splitText(string text)
        {
            List<string> lines = new List<string>();
            int startIndex = 0;
            int endIndex = 0;
            int lastSpaceIndex = -1;
            int lineLength = 40;
 
            while (startIndex < text.Length)
            {
 
 
                string lineToCheck ="";
 
                if ((startIndex + lineLength)<text.Length)
                {
                    lineToCheck = text.Substring(startIndex, lineLength);
                }
                else
                {
                    lineToCheck = text.Substring(startIndex);
                }
                string lineToAdd = "";
                lastSpaceIndex = lineToCheck.LastIndexOf(" ");
 
                if (lastSpaceIndex > -1)
                {
                    lineToAdd = lineToCheck.Substring(0, lastSpaceIndex);
                }
                else
                {
                    lineToAdd = lineToCheck;
                }
                lines.Add(lineToAdd);
                startIndex += lineToAdd.Length +1 ;
            }
            // print to output to see
            foreach(string line in lines){
                System.Diagnostics.Debug.WriteLine(line);
            }
 
            return lines;
 
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            splitText(this.textBox1.Text);
        }

Open in new window

Fundamentals of JavaScript

Learn the fundamentals of the popular programming language JavaScript so that you can explore the realm of web development.

HainKurtSr. System Analyst

Commented:
anarki_jimbelDate, the one posted is almost the same as the one I had posted :)

Author

Commented:
Okay, nearly there but it's not quite formatting the output correctly.

The code I have is below.  I've left out the bits not applicable to the wrapping.

The output in the text file is coming out as....

A24"908978","00","1234","0000","100      Testing the subject line"
A24"908978","00","1234","0001","Testing the first paragraph of the"
A24"908978","00","1234","0002","message body.  This text is coming from"
A24"908978","00","1234","0003","a text box that has the wrap feature"
A24"908978","00","1234","0004","enabled.

This is my second paragraph"
A24"908978","00","1234","0005","with a bit more text in.

And then my"
A24"908978","00","1234","0006","3rd and final"
A24"908978","00","1234","0007","paragraph."


I need to modify the code so that it appears like this.....

A24"908978","00","1234","0000","100      Testing the subject line"
A24"908978","00","1234","0001","Testing the first paragraph of the"
A24"908978","00","1234","0002","message body.  This text is coming from"
A24"908978","00","1234","0003","a text box that has the wrap feature"
A24"908978","00","1234","0004","enabled.
A24"908978","00","1234","0005",""
A24"908978","00","1234","0006","This is my second paragraph"
A24"908978","00","1234","0007","with a bit more text in."
A24"908978","00","1234","0008",""
A24"908978","00","1234","0009","And then my 3rd and final"
A24"908978","00","1234","0010","paragraph."

I don't understand exactly where it is going wrong but the wrap feature of the text box in the designer seems to perhaps be throwing it off somewhat as why is this happening when it is input on the same line in the text box...
And then my"
A24"908978","00","1234","0006","3rd and final"
A24"908978","00","1234","0007","paragraph."


Hope you can help.
        private List<string> splitText(string text)
        {
            List<string> lines = new List<string>();
            int startIndex = 0;
            int endIndex = 0;
            int lastSpaceIndex = -1;
            int lineLength = 40;
 
            while (startIndex < text.Length)
            {
                string lineToCheck = "";
 
                if ((startIndex + lineLength) < text.Length)
                {
                    lineToCheck = text.Substring(startIndex, lineLength);
                }
                else
                {
                    lineToCheck = text.Substring(startIndex);
                }
                string lineToAdd = "";
                lastSpaceIndex = lineToCheck.LastIndexOf(" ");
 
                if (lastSpaceIndex > -1)
                {
                    lineToAdd = lineToCheck.Substring(0, lastSpaceIndex);
                }
                else
                {
                    lineToAdd = lineToCheck;
                }
                lines.Add(lineToAdd);
                startIndex += lineToAdd.Length + 1;
            }
 
            return lines;
 
        }
 
private void sendButton_Click_1(object sender, EventArgs e)
{
 
List<string> lines = splitText(this.MessageTextBox.Text);
 
foreach (string line in lines)
{
sw.WriteLine("A24\"" + iTriqDate + "\",\"00\",\"" + MessageID + "\",\"" + String.Format("{0:0000}", LineCounter) + "\",\"" + line + "\"");
                                    LineCounter++;
}
}

Open in new window

anarki_jimbelSenior Developer

Commented:
"anarki_jimbelDate, the one posted is almost the same as the one I had posted :)"

Exactly, HainKurt :) I looked at the first solution and decided to add space handling. Did it and posted it :) Same as you :)
Senior Developer
Commented:
see the updated code below.

By the way, I believe that the last line should appear in one line: "And then my 3rd and final paragraph.",
and not in two lines as in your example (which is misleading).

        private List<string> splitText(string text)
        {
            List<string> lines = new List<string>();
            int startIndex = 0;
            int endIndex = 0;
            int lastSpaceIndex = -1;
            int lineLength = 40;
 
            string[] newLineSeparators = {Environment.NewLine};
            string[] paragraphs = text.Split(newLineSeparators, StringSplitOptions.None);
 
            foreach (string paragraph in paragraphs)
            {
                if (paragraph.Length = 0)
                {
                    lines.Add("");
                    continue;
                }
                
                startIndex = 0;
 
                while (startIndex < paragraph.Length)
                {
 
 
                    string lineToCheck ="";
 
                    if ((startIndex + lineLength)<paragraph.Length)
                    {
                        lineToCheck = paragraph.Substring(startIndex, lineLength);
                    }
                    else
                    {
                        lineToCheck = paragraph.Substring(startIndex);
                    }
                    string lineToAdd = "";
 
                    lastSpaceIndex = lineToCheck.LastIndexOf(" ");
 
                    if (lineToCheck.Length < lineLength)
                    {
                        lineToAdd = lineToCheck;
                    }
                    else if (lastSpaceIndex > -1)
                    {
                        lineToAdd = lineToCheck.Substring(0, lastSpaceIndex);
                    }
                    else
                    {
                        lineToAdd = lineToCheck;
                    }
                    lines.Add(lineToAdd);
                    startIndex += lineToAdd.Length +1 ;
                }
            }
 
            foreach(string line in lines){
                System.Diagnostics.Debug.WriteLine(line);
            }
 
            return lines;
 
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string text = @"100      Testing the subject line" + Environment.NewLine +
                            "Testing the first paragraph of the message body.  This text is coming from a text box that has the wrap feature enabled." +
                            Environment.NewLine + Environment.NewLine + "This is my second paragraph with a bit more text in." + Environment.NewLine +
                            Environment.NewLine + "And then my 3rd and final paragraph.";
 
            splitText(text);
        }

Open in new window

Commented:
try this code:

public string[] SplitStringByLengh(string strValue, int length)
{
      string[] array = new string[strValue.Length/length];
      int k=0;
      
      if(!string.IsNullOrEmpty(strValue))
      {
            do
            {
                  array[k] = strValue.Substring(0, length);
                  array[k] = array[k].Replace(Environment.NewLine, ""); // remove any extra new line within the string
                  strValue = strValue.Substring(length);
                  k++;
            }
            while(strValue.Length > 80);
            return array;
      }
      else
      {
            return null;
      }
}

string arrNewString = string.Join(System.Environment.NewLine, SplitStringByLengh(txtBox.text, 40));

now write newString.ToString() to the file...

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial