views:

154

answers:

3

In Java there is a nice class called Scanner for reading strings and streams of a certain format to data-structures like integers, floats,... Is there any equivalent in Mono? In .Net there is a binary-reader, but it reads the data as binaries. I want a class that read the data by parsing it from a string.

EDIT: reaction on the current answers, I know most of the data-types have a parse-method, but the problem with these are, they don't read the string sequentially. In Java you simply initialize the object, and by activating methods, you sequentially read the data-types.

+1  A: 

Most basic data types will have a .Parse and .TryParse() methods that will do that for you.

For example the Int32.TryParse method.

Oded
+1  A: 

In .NET, many of the type have static .Parse() and .TryParse() methods that takes a String parameter.

You could do something like:

Stream s = new Stream();
// Wire up the stream.

StreamReader reader = new StreamReader(s);
String value = reader.ReadToEnd();

int valueAsInt = Int32.TryParse(value);
Justin Niessner
+1  A: 

Well, since you are reading a file in for test cases, I'm going to assume you know the exact format of the data coming in and how it needs to be parsed. Looking at Java's Parser class in the documentation does make it look very complicated or much more than a convenience class. It appears to just tokenize the stream string on spaces and provide functions for taking the token and parsing it. And as far as I know, .Net doesn't have an equivalent class. So if you want one for reuse, then you'll need to write one yourself.

But the basic algorithm you need is to read the file contents, split the tokens, and parse them. If your file is reasonable sized, you could use File.ReadAllLines() which reads the contents of the file line-by-line into a String[]. Or you could use a StreamReader class to read the lines one at a time using its ReadLine(). Then once you have them in a line, you would tokenize them with String's Split(), and then parse them.

Not knowing exactly how you need to use the values in the file, a very basic pattern could be:

// Read in the whole file
String[] strLines = File.ReadAllLines(strFilePath);

// Loop through each of the lines to process their contents
foreach (String strLine in strLines) {
    // Tokenize on the spaces
    String[] strTokens = strLine.Split(' ');

    // Parse the values
    int iIntValue = Int.Parse(strTokens[0]);
    double dDoubleValue = Double.Parse(strTokens[1]);

    // Do something with the values
}

Creating your own Parser class would allow you to maintain the state and auto advance tokens as you use them. If you go that route, the StreamReader may be the best option.

CuppM