我想使用split函数将字符串分成两部分。问题是如何将第一部分和第二部分保存为两个不同的字符串数组以供进一步使用?
我要处理的文字是姓名,文件路径
Dim clientArr() as string
Dim FileArr() as string
FileOpen(1, strpath & "Location.txt", OpenMode.Input)
Do Until EOF(1)
Templine = LineInput(1)
Dim DataArr() As String = Templine.Split(",")
ClientArr = DataArr(0)
FileArr = DataArr(1)
loop
错误表明字符串不能用于1 D数组
谢谢
答案 0 :(得分:1)
这是21世纪,除了飞行汽车和机器狗之外,我们还可以轻松地将2大套相关数据放在一个单个容器中,但可以单独引用:< / p>
Class myFileParts
public Property FileName As String
public Property FilePath As String
Public Sub New(fName as string, fPath as String)
FileName = fName
FilePath = fPath
End Sub
End Class
' a container to hold lots of these
Friend myFiles As New List(Of myFileParts)
' filling it up:
Dim TempLine As String
Dim myF As myFileParts
Do Until EOF(1)
Templine = LineInput(1)
Dim DataArr() As String = Templine.Split(",")
' create a file item
f = New myFileParts(DataArr(0),DataArr(1))
' add to container
myFiles.Add(f)
loop
使用一个:(N是所需文件信息的索引):
Dim thisFile As string = MyFiles(N).FileName
Dim thisPath As string = MyFiles(N).FilePath
将它们打印出来:
For each f As myFileParts in myFiles
Console.WriteLine(String.Format("Path = {0}; Name = {1}",
f.FilePath, f.FileName)
Next f
答案 1 :(得分:0)
在开始之前,您知道文件中有多少行吗?如果没有,你可以使用List类做这样的事情:
Dim clientPart As List(Of String) = New List(Of String)()
Dim filePart As List(Of String) = New List(Of String)()
FileOpen(1, strpath & "Location.txt", OpenMode.Input)
Do Until EOF(1)
Templine = LineInput(1)
Dim DataArr() As String = Templine.Split(",")
clientPart.Add(DataArr(0))
filePart.Add(DataArr(1))
Loop
Dim clientPartStringArray As String() = clientPart.ToArray() 'If you really want an array
如果您这样做,则需要将每个拆分分配到clientArr
和fileArr
的元素,如:
Dim numLinesInFile As Integer 'If you know this value
Dim curIndex As Integer = 0
Dim clientArray(numLinesInFile) As String
Dim fileArray(numLinesInFile) As String
FileOpen(1, strpath & "Location.txt", OpenMode.Input)
Do Until EOF(1)
Templine = LineInput(1)
Dim DataArr() As String = Templine.Split(",")
clientArray(curIndex) = DataArr(0)
fileArray(curIndex) = DataArr(1)
curIndex = curIndex + 1
Loop
请注意代码中的差异:
clientArray
和fileArray
(您需要提前知道 - 如果您不知道/不能知道这个,请考虑使用像List
如先前提到的那样)Split
获得的字符串分配到由curIndex
表示的数组的特定索引curIndex
递增1,以便我们写入clientArray
和fileArray
中的空插槽...否则您只需写入相同的索引(0 )每次答案 2 :(得分:0)
问题是您将ClientArr和FileArr声明为字符串数组,这是您想要的,但是您尝试为它们分配字符串值。 DataArr(0)是一个字符串值。您需要将该vcalue放入ClientArr中的一个数组元素中。例如。 CleintArr(5)= DataArr(0)。
如果您知道循环之前文件中的确切行数,那么您可以声明CleintArr和FileArr的数组大小。然后你将使用一个在循环中获得增量的索引来设置正确的数组元素。
但是这是一种更好的方法,可以在不事先知道文件大小的情况下工作。这使用字符串集合来累积客户端和文件,然后在读取文件后将它们转换为数组。
Dim clientArr() As String
Dim FileArr() As String
Dim ClientList As New List(Of String)
Dim FileList As New List(Of String)
FileOpen(1, strpath & "Location.txt", OpenMode.Input)
Do Until EOF(1)
Templine = LineInput(1)
Dim DataArr() As String = Templine.Split(",")
ClientList.Add(DataArr(0))
FileList.Add(DataArr(1))
Loop
clientArr = ClientLIst.ToArray()
FileArr = FileList.ToArray()