我一直在阅读论坛,并努力寻找任何真正帮助我解决问题的帖子,所以我写的是最后的手段
我有一个包含此数据的文本文件:
Jones 14
Abrams 15
史密斯19 琼斯9Alexander 22
史密斯20 史密斯17Taylor 42
琼斯2
Hooper 12
琼斯11我需要按字母顺序排列名称,然后使用重复的名称,按编号(也称为年龄)按升序排序
我首先尝试执行readalllines函数,然后将这些行放入数组中,代码如下:
Dim orfi As String = "P:\names_ages.txt"
arrline() = File.ReadAllLines(orfi)
然后我尝试通过split函数拆分行,其中空格是分隔符:
Split(arrline(), " ")
尝试这个时,我不断收到一个错误,告诉我我无法拆分数组中的字符串,这使我感到困惑,现在我不知道如何根据名称和数据将这些数据转换为2D数组年龄。
如果有人有任何想法,我会感激不尽
完整代码:
Imports System.IO
模块模块1
Sub Main()
Dim info(name, age) As Integer
Dim orfi As String = "P:\names_ages.txt"
Dim c As Integer
Dim loopswap As Boolean
Dim temp As Integer
Dim maxIndex As Integer
Dim arrline() As String
maxIndex = arrline.Length - 1
'attempting to put lines into an array
Sub Main()
Dim lines() As String = File.ReadAllLines("P:\names_ages.txt")
Dim values(lines.Length - 1, 1) As String
For i As Integer = 0 To lines.Length - 1
Dim parts() As String = lines(i).Split(" ")
values(i, 0) = parts(0)
values(i, 1) = parts(1)
Next
'parsing file lines into an array and then further parsing them?
arrline() = File.ReadAllLines(orfi)
Split(arrline(), " ")
'bubble that sorts each line alphabetically
Do
loopswap = False
For c = 0 To maxIndex - 1
If arrline(c) > arrline(c + 1) Then
temp = arrline(c)
arrline(c) = arrline(c + 1)
arrline(c + 1) = temp
loopswap = True
End If
Next
Loop While loopswap
'bubble that sorts each line depending on age in ascending order
End Sub
结束模块
答案 0 :(得分:0)
这大致是您想要的,它并不完美,但它可以让您更好地了解所需要的内容。我已经添加了一个结构来保持组织有序。
如果您对sr.peek()
感到好奇,请参阅:StreamReader.Peek()
希望这有帮助。
Imports System.IO
Module Module1
Sub Main()
dim fileContents as List(Of CustomerInfo) = ReadFile("c:\names_ages.txt")
for each customer As CustomerInfo In fileContents
console.WriteLine("Name: " + customer.Surname & ", Age: " & customer.age.ToString())
Next
Console.ReadLine()
End Sub
Structure CustomerInfo
Dim Surname As String
Dim Age As Integer
End Structure
Private Function ReadFile(path As String) As List(Of CustomerInfo)
Dim custInfo As New List(Of CustomerInfo)
Dim sr As StreamReader = New StreamReader(path)
Do While sr.Peek() >= 0 'Check that the new line contains a character
Dim ci As New CustomerInfo
Dim customer As New List(Of String) 'Declare a new list
customer = sr.ReadLine().Split(" ").ToList() 'Split string and call ToList()
ci.Surname = customer(0).Trim() 'Select First element in list
ci.Age = customer(1).ToString().Trim() 'Select second element in list
'This is not a robust way to do things... It relies on data fitting a very specific format.
custInfo.Add(ci) 'Add structure to the list of customerInfo
Loop
Return custInfo
End Function
End Module
至于排序......我不确定你是否允许使用Linq
,但这是一种排序(不是冒泡排序,授予......)
Dim sortedList = From f In fileContents Order By f.Surname