Write a program that will break a long text at a particular position interval being specified

Niladri.Biswas
Posted by Niladri.Biswas under C# category on | Points: 40 | Views : 1153
Recently a colleague of mine approached to me and ask me that he has a requirement where he is reading a huge string of data and that needs to be break into a newline at a particular position (this is again configurable). I have written a pseudo code for him which is as under

static void Main(string[] args)
{
var input = "abcdefghijklmnoppqrstuvwxyz. I am great and so you are".ToCharArray();
var breakAtPosition = 4;
StringBuilder sb = new StringBuilder();

for (int i = 0; i < input.Length; i++)
{
sb.AppendLine(input.Skip(i).Take(breakAtPosition).Aggregate("", (a, b) => a + b));
i = i + (breakAtPosition - 1);
}
Console.WriteLine(sb.ToString());
Console.ReadKey();
}


Here we are breaking the long words at the fourth position. Let us understand the code. Initially we have converted the supplied string to a character array. In the first case when the loop ran, the value of
 i=0
and
breakAtPosition = 4
. So
sb.AppendLine(input.Skip(i).Take(breakAtPosition)
will yield "a b c d" and then the Aggregate Operator will use these characters and join them into a single string. The new value of "i" will be

 i = i + (breakAtPosition - 1);

i.e. i = 0 + (4-1) = 3.

When again the loop run, "i" value gets an increment to 4 and the
Skip
operator has skipped the first four charterers (i.e. "a b c d ) and the
Take
operator has fetched the next four characters (i.e. "e f g h"). and in this way the logic repeats until the condition turns out to be false. The final output is as under

Output

abcd
efgh
ijkl
mnop
pqrs
tuvw
xyz.
I a
m gr
eat
and
so y
ou a
re

Comments or Responses

Login to post response