2015-09-18 15 views
0

我正在建立一些簡單的東西,但已經有一個錯誤。如何在運行代碼後使用某個名稱來描述新數組?

總結:當我的代碼運行用戶將寫一些句子到cmd,我的代碼將它分離成單詞。 到目前爲止,這是沒問題的。分離後,我想使陣列的每個字 例如:

cmd screen =" hello world " 
seperating to words = hello , world 
making them arrays (program should do these aoutomatically) 
string[] hello = new string[5] 

string[] world = new string[5] 

這是問題的開始。我想在運行後命名這些新陣列。你會寫「蘋果」CMD和新名稱「蘋果」陣列應彈出。已經向我的老師詢問這個問題,他說可以用動態貴重物品(var等)來完成。但我不知道如何。在這裏我的代碼到目前爲止:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Collections; 
using System.Text.RegularExpressions; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      List<string> tümkelimeler = new List<string>(); 


      for (int i = 1; i < 100; i++) 
      { 
       tümkelimeler.Insert(i, "null"); 
      } 

      int ü = 0; 
      while (ü == 0) 
      { 

       string s = Console.ReadLine(); 


       string[] kelimeler = s.Split(' '); 
       // this is where i seperate words from sentence . 


      } 

Console.ReadKey() ; 
     } 

    } 
} 

    #Complete Code 
+0

就這麼你知道,你幾乎不想這樣做。永遠。 *特別*當你剛剛學習時。這種代碼反映了糟糕的設計/實踐。 – BradleyDotNET

回答

0

我正在展示一種使用動態ExpandoObject的方法。我們不斷添加具有字符串名稱和數組值的動態屬性。

顯示一句話,你可以運行一個循環,併爲你想要的儘可能多的句子。

using System.Dynamic; 

string s = "hello world"; //example 
IDictionary<string, object> dynamicArrays = new ExpandoObject(); 

string[] words = s.Split(' '); //hello, world 
foreach(var word in words) 
{ 
    dynamicArrays[word] = word.Select(c => new String(new char[] { c })).ToArray(); 
} 

它在循環的是:對於每一個字,它會在對象字作爲名稱的新特性(例如「你好」)。然後它將同一個單詞分解爲一個字母(字符串)數組(h,e,l,l,o)並將其作爲相同屬性的值添加。

如果看到動態對象dynamicArrays,它將具有以下屬性

hello: ['h', 'e', 'l', 'l', 'o'] 
world: ['w', 'o', 'r', 'l', 'd'] 

這裏查看ExpandoObject參考。


更新

如果你想這樣做多個用戶輸入,你可以這樣做。

static void Main(string[] args) 
{ 
    string s = string.Empty; 
    IDictionary<string, object> dynamicArrays = new ExpandoObject(); 

    Console.WriteLine("Keep entering words/sentences. Enter blank/empty line to end."); 
    s = Console.ReadLine(); 

    while (!string.IsNullOrEmpty(s)) 
    { 
     string[] words = s.Split(' '); //hello, world 
     foreach (var word in words) 
     { 
      dynamicArrays[word] = word.Select(c => new String(new char[] { c })).ToArray(); 
     } 
     Console.WriteLine("Enter next sentence : "); 
     s = Console.ReadLine(); 
    } 

    // do something with dynamicArrays 
    return; 
} 

在這裏,如果您輸入以下三個值:hello worldapplegreen tiger那麼這是什麼,你會在dynamicArrays對象中獲取。

{ 
    "hello": [ "h", "e", "l", "l", "o" ], 
    "world": [ "w", "o", "r", "l", "d" ], 
    "apple": [ "a", "p", "p", "l", "e" ], 
    "green": [ "g", "r", "e", "e", "n" ], 
    "tiger": [ "t", "i", "g", "e", "r" ] 
} 
+0

謝謝你的詳細解答。但如何做到這一點cmd screen =「你好世界」 單詞=你好,世界 字符串[] x =新字符串[5]運行代碼後,我會寫「蘋果」的控制檯。和「x」將成爲「蘋果」。 –

+0

@EnesKuz我不確定我是否正確理解它,但如果您想要接受多個用戶輸入併爲所有輸入執行此操作,請參閱我的**更新** -ed答案 –

相關問題