2015-05-04 74 views
-2

例如我有這樣的字符串:「是否允許進入這個房間而不詢問?」如何用換行符替換字符串中的每個第3個或第4個字符? C#

我想將每個第3或第4個換行符變成:「允許(換行符)不用詢問就換入(換行符)嗎?」

+0

這是學校裏的功課?你有沒有寫過任何代碼? –

+0

沒有一個Unity項目,我想在屏幕上顯示問題並使其合適。我曾經這樣做,手動添加'@'到'換行'但沒有成功。 – Kostikoglu

+0

你知道還有其他的方式來包裝文字嗎? –

回答

2

下面是一個非常詳細的解決方案,基於這樣的假設:每個單詞只與一個空格分隔。

var splitted = "Is it allowed to enter this room without asking?".Split(' '); 
StringBuilder str = new StringBuilder(); 
int i = 1; 
foreach (var word in splitted) 
{ 
    str.Append(word); 
    if (i % 3 == 0) 
    { 
     str.Append(System.Environment.NewLine); 
    } 
    else 
    { 
      str.Append(" "); 
    } 
    i++; 
} 

var result = str.ToString(); 
+0

代碼中代表什麼? (C#) – Kostikoglu

+0

隱式變量聲明https://msdn.microsoft.com/en-us/library/bb383973.aspx您可以用'string'替換它,它是一樣的。 –

0
static void Main(string[] args) 
    { 
     const string text = "Is it allowed to enter this room without asking?"; 
     string newText = null; 
     int count = 0; 
     foreach (char c in text) 
     { 
      string temp = c.ToString(); 
      if (c == ' ') 
      { 
       count ++; 
       bool placeNewLine = false; 
       Random random = new Random(); 
       if (random.Next(0, 2) == 1) placeNewLine = true; 
       if (count == 4 || (placeNewLine && count ==3)) 
       { 
        temp = Environment.NewLine; 
        count = 0; 
       } 
      } 
      newText += temp; 
     } 

     Console.WriteLine(newText); 
     Console.ReadLine(); 
    } 
+0

完美的解決方案! – Kostikoglu

相關問題