2013-11-28 56 views
1

我正在寫一個程序來擾亂用戶輸入的短語。我大部分都是編碼的,但是我想將用戶輸入的短語的字符串存儲到數組中,並將短語的每個單詞存儲爲一個單獨的元素。 這似乎是一件簡單的事情,但我無法想出一個辦法。有人能幫我嗎?C#如何將用戶輸入的短語存儲到字符串數組中?

這是什麼樣子至今:

static void Main(string[] args) 
    { 
     bool success = false; 
     string phrase = ""; 
     string [] phraseArray; 

     Console.WriteLine("Welcome to the Word Scrambler!\n\n"); 
     do 
     { 
      Console.WriteLine("Enter a phrase between 10 and 60 character long:\n\t"); 
      phrase = Console.ReadLine(); 
      if (phrase.Length - 1 <= 10 || phrase.Length - 1 >= 60) 
      { 
       Console.WriteLine("You must enter a phrase with a length between 10 and 60!"); 
       success = false; 
      } 
      phraseArray = new string[phrase.Length - 1]; 

      // String (phrase) into string [] phraseArray ? 

      Console.WriteLine("See below for your scrambled phrase:"); 
      for (int i = 0; i < phrase.Length - 1; i++) 
      { 
       Console.Write("{0} ", phraseArray[i]); 
      } 

      Console.WriteLine("Press any key to scramble another word or the 'Esc' key to exit..."); 
      if (Console.ReadKey(true).Key == ConsoleKey.Escape) 
       success = false; 
     } while (!success);` 
+0

使用string.Split()。 –

+0

第一次:成功=假;您需要添加一箇中斷來停止運行代碼的其餘部分。 –

回答

1
phraseArray = phrase.Split(); 

或者您需要刪除空字符串

phraseArray = phrase.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries); 
2

考慮以下...

string[] words = sentence.Split(' '); 

祝您好運!

+0

好的。謝謝大家。這真的很快! –

0

要保存短語每次只是這樣做:

phrase+= inputString + ";"; 

之後,你可以拆分短語,字符串數組:

string[] yourStringArray = phrase.split(';'); 
相關問題