2017-06-03 67 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

我以后如何与您联系? –