Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert newline character after specific number of words

Tags:

string

c#

I want to insert a new line character(\n) after 9 words in my string such that the string after the 9th word is in next line.

string newline="How to insert newline character after ninth word of(here) the string such that the remaining string is in next line"

Stucked here:

foreach (char x in newline)
{
    if (space < 8)
    {                    
        if (x == ' ')
        {
            space++;
        }
    }

}

Don't know why I got stucked. Its quite simple I know.
If possible, show any other simple method.

Thank you!

Note: Found an answer for myself. Given by me below.

like image 615
Ashish Sharma Avatar asked Dec 01 '22 17:12

Ashish Sharma


1 Answers

For what it's worth, here's a LINQ one-liner:

string newline = "How to insert newline character after ninth word of(here) the string such that the remaining string is in next line";
string lines = string.Join(Environment.NewLine, newline.Split()
    .Select((word, index) => new { word, index})
    .GroupBy(x => x.index / 9)
    .Select(grp => string.Join(" ", grp.Select(x=> x.word))));

Result:

How to insert newline character after ninth word of(here)
the string such that the remaining string is in
next line
like image 162
Tim Schmelter Avatar answered Dec 04 '22 05:12

Tim Schmelter