首页 > 解决方案 > 字符串数组到整数数组的转换

问题描述

我在将字符串数组(以前从 .txt 文件加载)转换为整数 1 时遇到问题。文件有 100 个随机数,它们加载没有任何问题,我只需要将它们转换为整数即可使用 3 种排序类型对它们进行排序。我已经尝试了很多这里所说的东西,但它们似乎都不起作用。我一直收到一个错误,说它无法转换。这是我从文件代码中加载的内容:

string[] path = File.ReadLines("C:\\Users\\M\\numb.txt").ToArray();
int[] numb= new int[path.Length];

for (int i = 0; i < path.Length; i++)
{
    Console.WriteLine(path[i]);
}

在选择了一些选项后,我使用 switch 来选择一个:

switch (a)
{
    case 1:
        Console.WriteLine("1. Bubble.");
        //int[] tab = numb; 
        babel(path);

        for (int z = 0; z < path.Length; z++)
        {
            Console.Write(path[z] + ", ");
        }
        break;

我的程序里也有冒泡排序的方法,觉得没必要在这里贴出来。

如果有人可以在这里帮助我,我将不胜感激。

@Amy - 我试过这个:

numb[i] = path[i].Convert.toInt32(); - it doesn't work.

我想要实现的是将这个数组中的每个数字都更改为int,我认为这里应该涉及到:

{
    Console.WriteLine(path[i]);
}

标签: c#

解决方案


这种转换有效。

#string[] path = File.ReadLines("C:\\Users\\M\\numb.txt").ToArray();    
String[] path = {"1","2","3"};
int[] numb = Array.ConvertAll(path,int.Parse);

for (int i = 0; i < path.Length; i++)
{
    Console.WriteLine(path[i]);
}

for (int i = 0; i < numb.Length; i++)
{
    Console.WriteLine(numb[i]);
}

推荐阅读