如何在每个\n
字符处拆分此字符串并用;
字符替换,最后将它们放在一个数组中。
之后,如果数组中的行超过60个字符,则再次拆分,就在char 60之前的最后一个空格中。然后在第二个部分仍然超过60个时重复?
我的代码是:
var testString = "Lorem Ipsum is simply dummy \n text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, \nwhen an unknown printer took a galley of \n type and scrambled \n it to make a type specimen";
const int maxLength = 60;
string[] lines = testString.Replace("\n", ";").Split(';');
foreach (string line in lines)
{
if (line.Length > maxLength)
{
string[] tooLongLine = line.Split(' ');
}
}
结果:
Lorem Ipsum简直是假的;
印刷和排版行业的文字。 Lorem Ipsum一直都是
自16世纪以来,行业的标准虚拟文本;
当一个未知的打印机拿走厨房时;
输入并加扰;
制作类型标本;
答案 0 :(得分:2)
首先,我要跟踪列表中的所需字符串。然后在\n
上拆分,并为每个结果字符串添加分号,然后检查它是否太长。然后诀窍是通过找到最大长度之前的最后一个空格来继续缩短字符串。如果没有空格,则只截断到最大长度。
string input = "Lorem Ipsum is simply dummy \n text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, \nwhen an unknown printer took a galley of \n type and scrambled \n it to make a type specimen";
int maxLength = 60;
List<string> results = new List<string>();
foreach(string line in input.Split('\n'))
{
string current = line.Trim() + ";";
int start = 0;
while(current.Length - start > maxLength)
{
int depth = Math.Min(start + maxLength, current.Length);
int splitAt = current.LastIndexOf(" ", depth, depth - start);
if(splitAt == -1)
splitAt = start + maxLength;
results.Add(current.Substring(start, splitAt - start));
while(splitAt < current.Length && current[splitAt] == ' ')
splitAt++;
start = splitAt;
}
if(start < current.Length)
results.Add(current.Substring(start));
}
foreach(var line in results)
Console.WriteLine(line);
该代码给出以下结果
Lorem Ipsum简直是假的;
印刷和排版行业的文字。 Lorem Ipsum
以来,
一直是业界的标准虚拟文本
1500年代,;
当一个未知的打印机拿走厨房时;
输入并加扰;
制作类型标本;
这与您的结果不同,因为您似乎允许超过60个字符,或者您可能只计算非空格。如果您真正想要的话,我会留给您更改。