2017-06-03 62 views
-2

我有號碼:241233 如何將此號碼拆分爲單獨的數字? 類似於: a = 2,b = 4,c = 1,d = 2,e = 3,f = 3 我可以在C#中做到這一點? (VisualStudio中2013) PS:數字改變每一次,但我知道它有6位如何將數字拆分爲C中的數字#

+0

你嘗試過什麼到目前爲止 – Nkosi

+1

我投票關閉這個問題作爲題外話,因爲「gimme teh codez」 – EJoshuaS

回答

0

我認爲您的解決方案是一個字典,一本字典有重點價值每個項目。

可以存儲每個項目(數),在一個字母,例如,A = 1。

首先,你建立這將您的數字轉換在字典的方法,

 public static void split(string number) 
     { 
     Dictionary<string, string> dict = new Dictionary<string, string>(); 
     string s = "ABCDEF"; 

     for (int i = 0; i < 6; i++) 
     { 
      dict.Add(s[i].ToString() , number[i].ToString()); // Here you add each char of the string ABCDEF, to the value from each char of the number. In this case A=2. 
      Console.WriteLine($"LETTER { s[i].ToString()} = { dict[s[i].ToString()] }"); // Here you print the values of your dictionary, if you want to call a value of your dictionary, you only have to say: dictionaryname[key], in this case, dictionaryname['A'] 
     } 

     } 

後,你打電話你的方法,你的方法的參數將是您要變換的數字。

static void Main(string[] args) 
     { 
      split("241233"); 
     } 

請一定要仔細閱讀代碼的評論//,

結果:

enter image description here

1
var collection = yourNumber.ToString().Select(c => Int32.Parse(c.ToString())); 
//or var collection = yourNumber.ToString().Select(Char.GetNumericValue); 

foreach(var num in collection) 
    Console.WriteLine(num); 
+0

以及如何顯示它?什麼是變量? –

+0

我編輯帖子 –

+0

@Mhai「數字每次變化」是什麼意思?答案因您嘗試做什麼而異。 –

0

您可以在數字轉換爲字符串,並獲得chararray,from the doc

String s = ... your 241233 as String; 
var chars = s.ToCharArray(); 
Console.WriteLine("Original string: {0}", s); 
Console.WriteLine("Character array:"); 
for (int ctr = 0; ctr < chars.Length; ctr++) 
    Console.WriteLine(" {0}: {1}", ctr, chars[ctr]); 
+0

我編輯文章 –

1

我會採取不同的方式,

沒有必要打破它爲字符數組。

你可以通過這個號碼的長度循環。 然後取數字和模10。

12345%10 = 1234,(給你最後一位數字,5)。 1234%10 = 123,(給你4) 等等......

我覺得它更優雅的解決方案,它應該是有點快於它分成字符數組,並投它爲int等,mod操作是原子操作,所以它比任何其他非原子操作都快。

+0

,但如果我的號碼每次都改變......你能給我代碼嗎?您的解決方案看起來非常好 –

+0

今天晚些時候我會收到,我現在不在,我從我的移動應用程序回答 – Roi1981

+0

我以後如何與您聯繫? –