I\'m new to programming and decided to take VB.net up as my first language, I\'m quite new and I\'m currently trying to write a sorting program. I\'m trying to load in a file, s
Using a regular expression to check for a match and extract the score values would be one option. Using File.ReadLines
(or File.ReadAllLines
pre .NET 4.0) will simplify the IO. You can also use LINQ to query for the matching lines and sort them:
Dim sortedScores =
From line in File.ReadLines("S:\class" & CName & ".rtf")
Let match = Regex.Match(line, "Score: (\d+)")
Where match.Success
Order By CInt(match.Groups(1).Value) Descending
Select line
For Each line In sortedScores
Console.WriteLine(line)
Next
You can remove the Descending
is you want lowest to highest.
If you want to extract the score values, you could modify the query slightly:
Dim justTheScores =
From line in File.ReadLines("S:\class" & CName & ".rtf")
Let match = Regex.Match(line, "Score: (\d+)")
Where match.Success
Select CInt(match.Groups(1).Value)
justTheScores
will be an IEnumerable(Of Integer)
containing just the scores.
More useful may be to extract the name and score:
Dim results =
From line in File.ReadLines("S:\class" & CName & ".rtf")
Let match = Regex.Match(line, "Name: (.*) \| Score: (\d+)")
Where match.Success
Select Name = match.Groups(1).Value, Score = CInt(match.Groups(2).Value)
This will give you an IEnumerable
of anonymous types with Name
and Score
properties.
Using currentfilereader As StreamReader = New StreamReader("S:\class" & CName & ".rtf")
Do
line = currentfilereader.ReadLine
If IsNumeric(line) AndAlso CInt(line) >= 1 AndAlso CInt(line)<= 10 Then
list.Add(line)
Console.WriteLine(line)
End If
Loop Until currentfilereader.EndOfStream
End Using
Since it seems all you are wanting is values 0 - 10, you can convert line to an integer and check if it is within that range.
AndAlso is a short-circuited comparison, meaning that as soon as one of your values is False, it'll stop comparing and carry on.
Also, you should make sure your readers end when they find EndOfStream, rather than when your line is Nothing.
This can be done much faster
Dim lines() As String = System.IO.File.ReadAllLines("S:\class" & CName & ".rtf")
For Each line as String in lines
' here I am not sure what you asking but you can do these to identify line
' Regex.Match("[0-9]+")
' line.contains...
' line.IndexOf...
' Do whatever you need with the line here
Next
You could try this to save every number of the file in a array:
Dim fileReader As StreamReader
fileReader = My.Computer.FileSystem.OpenTextFileReader("F:\\test.txt")
Dim numeros As New List(Of String)
Dim stringReader As String
stringReader = Convert.ToChar(fileReader.Read)
Do While (fileReader.Peek() >= 0)
stringReader = Convert.ToChar(fileReader.Read)
If stringReader Like "#" Then
numeros.Add(stringReader)
End If
Loop