Разбить строку на новую строку после слова N - PullRequest
1 голос
/ 02 декабря 2011

У меня длинная строка, я хочу разбить эту строку на новую строку после предварительно определенного количества слов.

Моя строка выглядит так:

Строка - это тип данных, используемый в программировании, такой как целое число и единица с плавающей запятой, но используемый для представления текста, а не чисел. Он состоит из набора символов, которые также могут содержать пробелы и цифры.

Я хочу разбить эту строку на новую строку после 50 символов.

Ответы [ 3 ]

4 голосов
/ 02 декабря 2011
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);
}
0 голосов
/ 02 декабря 2011
        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;
0 голосов
/ 02 декабря 2011

Тривиально, вы можете легко выполнить разбиение после 50 символов для этого простым:

    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));
    }

Ваш результат хранится в strings.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...