繁体   English   中英

将数据从文本文件拆分为并行数组

[英]Splitting data from a text file into parallel arrays

我的教授为该课程提供了一个C#示例,可用于从文本文件中分割数据。 我试图将它用于涉及拆分txt内容的项目。 归档到4个数组或字段中。 这是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

class Program
{
    static void Main()
    {
        int i = 0;
        foreach (string line in File.ReadAllLines("census.txt"))
        {
            string[] parts = line.Split(',');
            foreach (string part in parts)
            {
                Console.WriteLine("{0}",

                    part);
            }
            i++; 
        }
    }
}

这是census.txt

21,f, s, 14

41,f, m, 22

12, m, s, 12

11, f, s, 8

29, m, m, 4

6, m, s, 12

9, f, s, 2

30, f, s, 1

它应该是按年龄,性别,婚姻状况和地区划分的假设人口普查数据。 我一直得到的输出是单行中的每个数字或字符,如下所示:

21

f

s

14

41

f

m

22

等等。

我认为这意味着它正在工作,但我想知道如何使用它来进入4个并行数组。 我还想了解更多关于将它分成4个字段,结构或类的信息。 该项目的下一部分涉及每次出现某个年龄编号或地区编号时计数,这将涉及许多阵列。

我会稍微扩展一下irsog的答案:

  • 使用类而不是结构
  • 使用属性而不是字段
  • 使用GenderMaritalStatus枚举而不是纯字符串

码:

public class Person
{
    public int Age { get; set; }
    public MaritalStatus MaritalStatus { get; set; }
    public Gender Gender { get; set; }
    public int District { get; set; }
}

public enum MaritalStatus
{
    Single, Married
}

public enum Gender
{
    Male, Female
}

用法:

var people = new List<Person>();

foreach (string line in File.ReadAllLines("Input.txt"))
{
    string[] parts = line.Split(',');

    people.Add(new Person()  {
        Age = int.Parse(parts[0]),
        MaritalStatus = parts[1] == "s" ? MaritalStatus.Single : MaritalStatus.Married,
        Gender = parts[2] == "m" ? Gender.Male : Gender.Female,
        District = int.Parse(parts[3])
    });
}

这是旧线程,但谷歌在前几页中显示它我决定发送我的评论。 我强烈建议不要使用给定的txt文件格式,因为它不是错误证明。 如果census.txt不能保证是理想的,特别是如果它应该由某个第三方(用户,管理员,无论谁)创建,那么我强烈建议用一些符号结束记录,如:21,f,s ,14;

41,f,m,22; 然后我们做的第一件事 - 我们获得了一系列记录,如下所示:

string [] lines = text.split(';');

然后再简单拆分 - 这次是为了获得记录元素。

foreach(字符串记录)

{

string [] fields = record.split(',');

}

这样,它不仅更容易读取记录/字段,而且还可以轻松检查文件的一致性,忽略错误(空记录),检查每个记录中的字段数等。

您可以为所需信息创建结构:

public struct Info
{
    public int Age;
    public string gender;
    public string status;
    public int district;
}

并将数据插入结构列表:

  List<Info> info = new List<Info>();
    foreach (string line in File.ReadAllLines("census.txt"))
    {
        string[] parts = line.Split(',');

            info.Add(new Info() {Age=int.Parse(parts[0]), gender=parts[1], status=parts[2], district=int.Parse(parts[3]) });
    }

现在你有一个人员信息列表。

通用列表(在此处的其他2个当前答案中使用)是最佳方式。 但是,如果您需要将数据放在数组中(正如您之前的问题似乎表明的那样),那么您可以像这样修改教授的代码:

C#

int[] districtDataD = new int[900];
string[] districtDataG = new string[900];
string[] districtDataM = new string[900];
int[] districtDataA = new int[900];

int i = 0;
foreach (string line in File.ReadAllLines("census.txt"))
{
    string[] parts = line.Split(',');

    districtDataD[i] = int.Parse(parts[0]);
    districtDataS[i] = parts[1];
    districtDataM[i] = parts[2];
    districtDataA[i] = int.Parse(parts[3]);
    i++;
}

VB.NET(因为您的原始问题是用VB.NET标记的):

Dim districtDataD() As New Integer(900)
Dim districtDataS() As New String(900)
Dim distrcitDataM() As New String(900)
Dim districtDataA() As New Integer(900)

Dim i As Integer = 0

For Each Dim line As String In File.ReadAllLines("census.txt")
    Dim string() As parts = line.Split(',')

    districtDataD(i) = Integer.Parse(parts(0))
    districtDataS(i) = parts(1)
    districtDataM(i) = parts(2)
    districtDataA(i) = Integer.Parse(parts(3))

    i++
Next

您也可以使用structclass并拥有一个包含该对象的数组,但看起来您教授希望您使用4个单独的数组。 如果你可以使用一个,你可以简单地声明这个数组,例如:

C#

Person[] districtData = new Person[900];

VB.NET

Dim districtData() As New Person(900)

然后你可以在拆分逻辑中执行此操作(请注意,如果Distric和Age是对象中的整数,则必须按照我在下面显示的方式转换或解析它们):

C#

districtData[i] = new Person() { District = int.Parse(parts[0]), Gender = parts[1], MaritalStatus = parts[2], Age = int.Parse(parts[3]) };

VB.NET

districtData[i] = new Person() With { .District = Integer.Parse(parts[0]), .Gender = parts[1], .MaritalStatus = parts[2], .Age = Integer.Parse(parts[3]) }

此代码存在风险,如果您有超过900行数据,您将获得超出范围异常的索引。 避免这种情况的一种方法是使用while循环修改上面的代码,该循环检查目标数组的边界或者行数未超过,如下所示:

C#

string[] lines = File.ReadAllLines("census.txt");
int i = 0;

while (i < 900 && i < parts.Length)
{

    // split logic goes here
}

VB.NET

Dim lines As String() = File.ReadAllLines("census.txt")
Dim i As Integer = 0

While (i < 900 AndAlso i < lines.Length)

    ' split logic goes here
End While

我没有测试过代码,但如果你必须使用数组,这将有助于你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM