在一行文本中提取int并进行拆分
本文关键字:int 提取 拆分 文本 一行 | 更新日期: 2023-09-27 18:20:55
我正试图将文本文件中的一行拆分为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);
}
假设"上映"是电影上映的年份,作为一个整数:
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);
}
您没有指定Movie的哪个成员是内部
这相当简单。例如,如果流派是你的int:
movie.genre = Convert.ToInt32(parts[1]);
我想你会发现有点困惑的是,在C#中,有Convert.ToInt32
、Int32.Parse
和Int32.TryParse
(这只是针对Int32
……所有其他int和类型都有更多的变体)
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);
}
您可以简单地将字符串解析为int
假设"release"应该被解析为整数,
movie.release = int.parse(parts[2]);
用你的代码说字符串是"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]);
这应该很好用。