2017-08-02 71 views
-1

如何在每个\n字符处拆分该字符串,并用;字符替换,最后将它们放入数组中。在c中剪切字符串#

之后,如果数组中的行长度超过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存有简直是虚拟;

印刷和排版行业的文字。 Lorem Ipsum已从

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

当一台未知的打印机拿走一个厨房的时候;

type and scrambled;

它制作一个型号的样本;

+4

你知道你可以只分割'\ n'而不是先做替换。 – juharr

+0

是的,但我需要用\ n替换\ n字符; –

+2

我很困惑..输出不是你所期望的吗? –

回答

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存有只是虚设;

印刷和排版行业的文字。 Lorem存有

一直是业界标准的虚拟文本自从

1500年,;

当一台未知的打印机拿走一个厨房的时候;

type and scrambled;

它制作一个型号的样本;

这与您的结果不同,因为您似乎允许超过60个字符,或者您可能只计算非空格。如果这是你真正想要的,我会留给你做出改变。

+0

未处理的异常信息:System.ArgumentOutOfRangeException:计数必须为正和计数必须引用位置的字符串/阵列/集合内。 –

+0

@PeterSmith是的,我有'LastIndexOf'设置错误。我现在修好了。 – juharr

+0

并且它需要一个数组 –