1

我正在尝试将文本文件中的一行拆分为 4 个字符串和 1 个 int。我不知道如何提取 int 部分。

有人可以帮我吗?

StreamReader infil = new StreamReader("moviefile.txt", Encoding.GetEncoding(28591));
for (;;)
{
    string line = infil.ReadLine();
    if (line == null) break;

    string[] parts = line.Split('\t');

    Movie movie = new Movie();
    movie.title = parts[0];
    movie.genre = parts[1];
    movie.release = parts[2];
    movie.actor = parts[3];
    movie.director = parts[4];

    AddMovie(movie);
}
4

5 回答 5

3

假设 'release' 是电影的发行年份,作为一个整数:

int release;
bool didParse;
while (true)
{
    string line = infil.ReadLine();
    if (line == null) break;

    string[] parts = line.Split('\t');

    Movie movie = new Movie();
    movie.title = parts[0];
    movie.genre = parts[1];
    didParse = Int.TryParse(parts[2], out release);
    movie.release = (didParse) ? release: -1;
    movie.actor = parts[3];
    movie.director = parts[4];

    AddMovie(movie);
}
于 2013-07-02T18:52:24.537 回答
1

您没有指定 Movie 的哪个成员是 int。

这很简单。例如,如果流派是您的 int:

 movie.genre = Convert.ToInt32(parts[1]);
于 2013-07-02T18:52:11.840 回答
0

我认为您会发现有点令人困惑的是,在 C# 中,有Convert.ToInt32, Int32.Parse, and Int32.TryParse(这只是为了Int32......所有其他整数和类型都有更多变体)

StreamReader infil = new StreamReader("moviefile.txt", Encoding.GetEncoding(28591));
for (;;)
{
    [...]
    movie.release = Int32.Parse(parts[2]);  // Parse parts[2] into an 32-bit (4-byte) integer.
    [...]    
    AddMovie(movie);
}
于 2013-07-02T18:53:49.420 回答
0

使用您的代码说字符串是“SomeTitle SomeGenre SomeRelease SomeActor SomeDirectore 2008”:

string[] parts = line.Split('\t');

Movie movie = new Movie();
movie.title = parts[0];
movie.genre = parts[1];
movie.release = parts[2];
movie.actor = parts[3];
movie.director = parts[4];
movie.year = int.Parse(parts[5]);

那应该工作得很好。

于 2013-07-02T18:54:15.833 回答
0

您可以简单地将字符串解析为 int

假设'release'应该被解析成整数,

movie.release = int.parse(parts[2]);
于 2013-07-02T18:55:14.697 回答