Insert a newline after a certain number of words

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

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

Stuck here:

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

}

I don’t know why I’m stuck. Its pretty simple I know.
If possible, indicate another easy way.

Thanks!

Note. Found an answer for yourself. Given by me below.

+4
source share
5 answers

For what it's worth, here's a single-line LINQ:

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
+12
source

This is one way:

List<String> _S = new List<String>();
var S = "Your Sentence".Split().ToList();
for (int i = 0; i < S.Count; i++) {
    _S.add(S[i]);
    if ((i%9)==0) { 
        _S.add("\r\n");       
    }
}
+4

StringBuilder :

string newline = "How to insert newline character after ninth word of(here) the string such that the remaining string is in next line";
StringBuilder sb = new StringBuilder(newline);
int spaces = 0;
int length = sb.Length;
for (int i = 0; i < length; i++)
{
    if (sb[i] == ' ')
    {
        spaces++;
    }
    if (spaces == 9)
    {
        sb.Insert(i, Environment.NewLine);
        break;
        //spaces = 0; //if you want to insert new line after each 9 words
    }

}

string str = sb.ToString();

In your current code, you increase the space counter, but do not compare it with 9, and then insert a new line.

+1
source

Have you tried Environment.NewLine paste? You can also use String.Split ("") to get an array of all btw words ...

0
source
string modifiedLine="";
int spaces=0;
foreach (char value in newline)
{
    if (value == ' ')
    {
        spaces++;
        if (spaces == 9) //To insert \n after every 9th word: if((spaces%9)==0)
        {
            modifiedLine += "\n";
        }
        else
            modifiedLine += value;
    }
    else
    {
        modifiedLine += value;
    }                
}
0
source

Source: https://habr.com/ru/post/1523424/


All Articles