我试图将文本文件中的一行拆分为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);
}
答案 0 :(得分: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);
}
答案 1 :(得分:1)
您没有指定Movie的哪个成员是int。
这很简单。例如,如果genre是你的int:
movie.genre = Convert.ToInt32(parts[1]);
答案 2 :(得分:0)
我认为您会发现有些令人困惑的是,在C#中,有Convert.ToInt32
,Int32.Parse
和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);
}
答案 3 :(得分: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]);
这应该可以正常工作。
答案 4 :(得分:0)
您可以简单地将字符串解析为int
假设'release'应该被解析为整数,
movie.release = int.parse(parts[2]);