-3

Hi I have a string paragraph containing 25 words and 300 characters, I want to set it in set of labels which can be contain 40 characters. I am trying it as below code with character lengths.

public static List<string> _mSplitByLength(this string str, int maxLength)
{
    List<string> _a = new List<string>();
    for (int index = 0; index < str.Length; index += maxLength)
    {
        _a.Add(str.Substring(index, Math.Min(maxLength, str.Length - index)));
    }
    return _a;
}

with above code i can split string into 40 character but problem is that it split words also.

suppose my string is "My school Name is stack over flow High school." which is 46 characters so with my code its getting like this

list 1 = "My school Name is stack over flow High s"
list 2 = "chool."

My question is how to split string on basis of words. if last word not comming so it should be transfer to next list.

my Aim is

list 1 = "My school Name is stack over flow High "
list 2 = "school."
Imran Ali Khan
  • 8,469
  • 16
  • 52
  • 77

1 Answers1

2

Try this:

string text = "My school Name is stack over flow High school.";
List<string> lines =
    text
        .Split(' ')
        .Aggregate(new [] { "" }.ToList(), (a, x) =>
        {
            var last = a[a.Count - 1];
            if ((last + " " + x).Length > 40)
            {
                a.Add(x);
            }
            else
            {
                a[a.Count - 1] = (last + " " + x).Trim();
            }
            return a;
        });

I get this out:

My school Name is stack over flow High 
school. 
Enigmativity
  • 113,464
  • 11
  • 89
  • 172