Reputation: 169
I am attempting to split a line from a text file into 4 strings and 1 int. I do not know how to extract the int part.
Can someone help me out here?
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);
}
Upvotes: 1
Views: 78
Reputation: 1540
Say the string is "SomeTitle SomeGenre SomeRelease SomeActor SomeDirectore 2008" using your code:
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]);
That should work just fine.
Upvotes: 0
Reputation: 11
You can simply parse a string to int
Assuming 'release' was supposed to be parsed into integer,
movie.release = int.parse(parts[2]);
Upvotes: 0
Reputation: 64682
I think what you'll find slightly confusing is that in C#, there is Convert.ToInt32
, Int32.Parse
, and Int32.TryParse
(and thats just for Int32
... there are more variations for all the other ints and types)
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);
}
Upvotes: 0
Reputation: 963
Assuming 'release' is the year the movie was released, as an integer:
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);
}
Upvotes: 3
Reputation: 3500
You didn't specify which member of Movie was an int.
It's fairly straightforward. For example, if genre was your int:
movie.genre = Convert.ToInt32(parts[1]);
Upvotes: 1