有任何方法可以将int转换为字符串,然后再次转换为int

问题描述 投票:0回答:2

我想得到一个数字的长度。我知道我可以使用while循环并除以10直到数字达到0,但是这需要大约10行代码,而且我认为这样做会更快,更高效。

使用系统;

        int[] array = new int[5]{1,12,123,1234,12345};
        int[] length = new int[array.Length];
        int i = 0;
        while (i < 0)
        {
            length[i] = int.Parse(((array[i]).ToString()).Length);
            i++;
        }
        i = 0;
        while (i < array.Length)
        {
            Console.Write("{0} ", length);
            i++;
        }

由于某种原因,我告诉它打印每个数字的代码长度,而不是仅打印system.int32 [] 5次就打印出length(1、2、3、4、5)

c# int tostring
2个回答
2
投票

您不必解析.Length,因为Length返回int;您的代码已修改:

  int[] array = new int[] {1, 12, 123, 1234, 12345};
  int[] length = new int[array.Length];

  for (int i = 0; i < array.Length; ++i)
    length[i] = array[i].ToString().Length;

  for (int i = 0; i < length.Length; ++i)
    Console.Write("{0} ", length[i]);

1
投票

这是因为length是一个数组,而不是实际项目(我想您要打印)。修复很容易,用Console.Write("{0} ", length);

替换Console.Write("{0} ", length[i]);
© www.soinside.com 2019 - 2024. All rights reserved.