Skip to main content
 首页 » 编程设计

c#之在 N 字后换行拆分字符串

2024年02月23日2898°冷暖

我有一个很长的字符串,想在预定义的字数之后在新行中断开该字符串。

我的字符串是这样的:

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.

我想在 50 个字符后将此字符串拆分为新行。

请您参考如下方法:

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