2017-08-02 69 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

並且它需要一個數組 –