Vijjendra
Vijjendra

Reputation: 25213

Split string in a new line after the N word

I have a long string, want to break that string in new line after a predefined word count.

My string is look like:

A string is a data type used in programming, such as an integer and floating point unit, but is used to represent text rather than numbers. It is comprised of a set of characters that can also contain spaces and numbers.

I want to split in to new line this string after a 50 character.

Upvotes: 1

Views: 3206

Answers (3)

sll
sll

Reputation: 62484

string text = "A string is a data type used in programming, such as an integer and floating point unit, but is used to represent text rather than numbers. It is comprised of a set of characters that can also contain spaces and numbers.";

int startFrom = 50;
var index = text.Skip(startFrom)
                .Select((c, i) => new { Symbol = c, Index = i + startFrom })
                .Where(c => c.Symbol == ' ')
                .Select(c => c.Index)
                .FirstOrDefault();


if (index > 0)
{
    text = text.Remove(index, 1)
        .Insert(index, Environment.NewLine);
}

Upvotes: 4

Orn Kristjansson
Orn Kristjansson

Reputation: 3485

        string thestring = "A string is a data type used in programming, such as an integer and floating point unit, but is used to represent text rather than numbers. It is comprised of a set of characters that can also contain spaces and numbers.";
        string sSplitted = string.Empty; 
        while (thestring.Length > 50)
        {
            sSplitted += thestring.Substring(1, 50) + "\n";
            thestring = thestring.Substring(50, (thestring.Length-1) -50);
        }
        sSplitted += thestring;

Upvotes: 0

George Johnston
George Johnston

Reputation: 32258

Trivially, you could easily accomplish splitting after 50 characters for this in a simple for:

    string s = "A string is a data type used in programming, such as an integer and floating point unit, but is used to represent text rather than numbers. It is comprised of a set of characters that can also contain spaces and numbers.";
    List<string> strings = new List<string>();
    int len = 50;
    for (int i = 0; i < s.Length; i += 50)
    {
        if (i + 50 > s.Length)
        {
            len = s.Length - i;
        }
        strings.Add(s.Substring(i,len));
    }

Your result being held in strings.

Upvotes: 0

Related Questions