2012-03-25 42 views
1

我需要一個句子,所有句子都在一行中,沒有空格,每個新詞都有一個字母EX。 「StopAndSmellTheRoses」,然後將其轉換爲「停止並聞到玫瑰」這是我的函數,但我一直在插入方法的參數超出範圍錯誤。感謝您提前提供任何幫助。C#修復語句

private void FixSentence() 
{ 
    // String to hold our sentence in trim at same time 
    string sentence = txtSentence.Text.Trim(); 

    // loop through the string 
    for (int i = 0; i < sentence.Length; i++) 
    { 
     if (char.IsUpper(sentence, i) & sentence[i] != 0) 
     { 
      // Change to lowercase 
      char.ToLower(sentence[i]); 

      // Insert space behind the character 
      // This is where I get my error 
      sentence = sentence.Insert(i-1, " "); 
     } 
    } 

    // Show our Fixed Sentence 
    lblFixed.Text = ""; 
    lblFixed.Text = "Fixed: " + sentence; 
} 

回答

3

建立以這種方式String最好的辦法是使用StringBuilder實例。

var sentence = txtSentence.Text.Trim(); 
var builder = new StringBuilder(); 
foreach (var cur in sentence) { 
    if (Char.IsUpper(cur) && builder.Length != 0) { 
    builder.Append(' '); 
    } 
    builder.Append(cur); 
} 

// Show our Fixed Sentence 
lblFixed.Text = ""; 
lblFixed.Text = "Fixed: " + builder.ToString(); 

使用Insert方法創建一個新string實例造成了很多不必要的分配值的每一次。 StringBuilder雖然不會實際分配String,直到您調用ToString方法。

+0

這個工作我看着更進建設者,這是挑釁的路要走。非常感謝 – amedeiros 2012-03-25 15:33:18

0

您不能在循環中修改句子變量。

相反,您需要有第二個字符串變量,您可以追加所有找到的單詞。

1

這裏是the answer

var finalstr = Regex.Replace(
     "StopAndSmellTheRoses", 
     "(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])|(?<=[^0-9])(?<x>[0-9])(?=.)", 
     me => " " + me.Value.ToLower() 
    ); 

將輸出

Stop and smell the roses 
0

另一個版本:

public static class StringExtensions 
{ 
    public static string FixSentence(this string instance) 
    { 
    char[] capitals = Enumerable.Range(65, 26).Select(x => (char)x).ToArray(); 
    string[] words = instance.Split(capitals); 
    string result = string.Join(' ', words); 
    return char.ToUpper(result[0]) + result.Substring(1).ToLower(); 
    } 
}