2014-01-23 258 views
4

我想在我的字符串中插入9個字之後插入一個換行符(\ n),以便第9個字之後的字符串在下一行中。在特定字數之後插入換行符

字符串換行=「如何將字符串(在這裏)第九字後插入換行符這樣剩餘字符串是下一行」

Stucked這裏:

foreach (char x in newline) 
{ 
    if (space < 8) 
    {      
     if (x == ' ') 
     { 
      space++; 
     } 
    } 

} 

不知道爲什麼我被困住了。我知道它很簡單。
如果可能,請顯示任何其他簡單的方法。

謝謝!

注意:爲自己找到了答案。由下面給出。

+2

你所包含的代碼並沒有做你說你想要完成的事情,它只會計數空間。請包括您嘗試的完整代碼。另外,請詳細說明您遇到的錯誤/問題,以便我們可以更好地爲您提供幫助。通常這樣的問題要求我們「請給我一個codez!」將關閉。 –

回答

4

這是一種方式:

List<String> _S = new List<String>(); 
var S = "Your Sentence".Split().ToList(); 
for (int i = 0; i < S.Count; i++) { 
    _S.add(S[i]); 
    if ((i%9)==0) { 
     _S.add("\r\n");  
    } 
} 
+1

使用'%'運算符+1。它被低估了。 –

12

對於它的價值,這裏有一個LINQ一行代碼:

string newline = "How to insert newline character after ninth word of(here) the string such that the remaining string is in next line"; 
string lines = string.Join(Environment.NewLine, newline.Split() 
    .Select((word, index) => new { word, index}) 
    .GroupBy(x => x.index/9) 
    .Select(grp => string.Join(" ", grp.Select(x=> x.word)))); 

結果:

How to insert newline character after ninth word of(here) 
the string such that the remaining string is in 
next line 
+0

如果我們需要插入兩個連續的換行符,該怎麼辦? –

+0

然後使用'string.Join(Environment.NewLine + Environment.NewLine,...'而不是 –

+0

你搖滾。Thanx很多.. –

1

使用StringBuilder,如:

string newline = "How to insert newline character after ninth word of(here) the string such that the remaining string is in next line"; 
StringBuilder sb = new StringBuilder(newline); 
int spaces = 0; 
int length = sb.Length; 
for (int i = 0; i < length; i++) 
{ 
    if (sb[i] == ' ') 
    { 
     spaces++; 
    } 
    if (spaces == 9) 
    { 
     sb.Insert(i, Environment.NewLine); 
     break; 
     //spaces = 0; //if you want to insert new line after each 9 words 
    } 

} 

string str = sb.ToString(); 

在您當前的代碼中,您只是遞增空間計數器,但不會將其與9進行比較,然後插入新行。

0
string modifiedLine=""; 
int spaces=0; 
foreach (char value in newline) 
{ 
    if (value == ' ') 
    { 
     spaces++; 
     if (spaces == 9) //To insert \n after every 9th word: if((spaces%9)==0) 
     { 
      modifiedLine += "\n"; 
     } 
     else 
      modifiedLine += value; 
    } 
    else 
    { 
     modifiedLine += value; 
    }     
} 
+0

這只是在第9個單詞之後插入一個新行字符和不是每9個單詞之後,是不是要求?另外,如果我使用一個循環,我會使用一個StringBuilder而不是字符串連接,效率較低。 –

+0

因此我們可以有: if((spaces spaces% 9)== 0) –

相關問題