C# 用c切掉字符串

C# 用c切掉字符串,c#,split,C#,Split,如何在每个\n字符处拆分此字符串并替换为;字符,最后将它们放入数组中 之后,如果数组中的行长度超过60个字符,则再次拆分,仅在字符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

如何在每个\n字符处拆分此字符串并替换为;字符,最后将它们放入数组中

之后,如果数组中的行长度超过60个字符,则再次拆分,仅在字符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已被删除

16世纪以来的行业标准虚拟文本

当一个不知名的印刷工拿走了一个厨房

类型和加扰

制作一个标本


首先,我将跟踪列表中所需的字符串。然后在上拆分\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);
该代码给出了以下结果

同侧眼睑只是一个假人

印刷和排版行业的文本。同侧眼睑

自上世纪90年代以来,一直是行业标准的虚拟文本

1500秒

当一个不知名的印刷工拿走了一个厨房

类型和加扰

制作一个标本


这与您的结果不同,因为您似乎允许超过60个字符,或者您可能只计算非空格。如果您真的想要更改,我将让您自行更改。

您知道您可以在\n上拆分,而不是先进行替换。我很困惑。。输出不是您期望的吗?@EastonBornemeier,但是string.Split会去掉分隔符,所以您只需要在分割后添加分号。您能给我们期望的结果吗,而不是给出您不想要的结果。如果您有一行长度超过60且没有空格,该怎么办?未处理的异常:System.ArgumentOutOfRangeException:Count必须为正,并且Count必须引用字符串/数组/集合中的某个位置。@PeterSmith是的,我的LastIndexOf设置错误。我现在已经修复了它。它需要是一个数组然后只需执行字符串[]myArray=results.ToArray;最后。仅供参考,我还需要修复它以截断它所打断的空间。我马上更新