我有一个长字符串,想要在预定义的字数统计后在新行中断开该字符串。
我的字符串如下:
字符串是编程中使用的数据类型,例如整数和浮点单元,但用于表示文本而不是数字。它由一组字符组成,这些字符也可以包含空格和数字。
我希望在50个字符之后将此字符串拆分为新行。
答案 0 :(得分:4)
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);
}
答案 1 :(得分:0)
琐碎的是,您可以轻松地在 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
。
答案 2 :(得分:0)
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;