2011-12-02 118 views
1

我有一個很長的字符串,想要在預定義的字數後打斷該字符串。將字符串拆分爲N個字後的新行

我的字符串是看起來像:

字符串是在編程中使用的,如一個整數和浮點單元的數據類型,而是用於表示文本而不是數字。它由一組可以包含空格和數字的字符組成。

我想在50個字符後分割成新的一行這個字符串。

+2

在單詞或字符數之後進行拆分?哪一個? – Icarus

+0

@lcarus:按字 – Vijjendra

+1

呃,在50個字和50個單詞之後,你打算如何拆分?這是沒有意義的。 – mattypiper

回答

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); 
} 
+0

我羨慕那些能夠使用.NET 3.5 + ...的人,但是在這方面的可讀性是痛苦的。 –

+0

不同意可讀性,也許你沒有經常使用LINQ,所以這對你來說很不尋常 – sll

+0

他正在使用Linq和Lambdas在非常簡潔的代碼中做一些強大的工作。編譯器和框架爲他做了大量的工作。你應該很羨慕這些1337技能。 – mattypiper

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舉行。

+0

爲什麼不使用StringBuilder,這樣他就可以.ToString()呢? –

+0

@Ryan他可以這樣做,'strings.Aggregate((i,j)=> i + Environment.NewLine + j)'如果他想要格式化的字符串。 –

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;