2015-07-06 15 views
0

新手在這裏停留在一個小問題上。 我只是做一個小的簡單任務來處理技能,但我不能解決這個小問題。 本質上,我通過一種方法解析一個句子字符串,將每個單詞分開並按字母順序排列每個單詞。然而,我無法弄清楚爲什麼第一個單詞永遠不會被alphabetizes。任何幫助深表感謝。字符串Alphabetizer - 不字母化的第一個詞

static string Alphabetize(string word) 
    { 
     char[] a = word.ToCharArray(); 

     Array.Sort(a); 

     return new string(a); 
    } 

    static void Scrambler(string sentence) 
    { 
     string tempStore = ""; 
     List<string> sentenceStore = new List<string>(); 
     Regex space = new Regex(@"^\s+$"); 


     // Store each word in a list 
     for (int c = 0; c < sentence.Length; c++) 
     { 
      if (!space.IsMatch(Convert.ToString(sentence[c]))) 
      { 
       tempStore += Convert.ToString(sentence[c]); 
       if (sentence.Length - 1 == c) 
       { 
        sentenceStore.Add(tempStore); 
       } 
      } 
      else 
      { 
       sentenceStore.Add(tempStore); 
       tempStore = ""; 
      } 
     } 


     foreach (string s in sentenceStore) 
     { 

      Console.Write(Alphabetize(s)); 
      Console.WriteLine(); 
     } 
    } 

    static void Main(string[] args) 
    { 
     Scrambler("Hello my name is John Smith"); 
    } 
+0

有你嘗試以單步模式調試您的程序,看看每個單詞會發生什麼?另外,請考慮使用'String.Split' – HugoRune

回答

1

它 「按字母順序排列」(排序)你的第一個字。 當與Array.Sort()「字母化」時,首先按字母順序排列大寫字母,然後按字母順序排列小寫字母。

所以"cCbBaA"例如應成爲"ABCabc"

"Smith"例如應成爲"Shimt"

"Hello"仍將"Hello"

在一個側面說明:您應該考慮使用String.Split()

+0

哦!好的,謝謝你。我實現了String.Split方法,工作完美。謝謝! – kristian

+0

@kristian歡迎您!如果它解決了您的問題,請隨時將我的答案標記爲「正確答案」。 (: –

相關問題