VB split的用法

我用VB5读取一个文本文件,由于需逐行读取再分析计算。可是这种读入文件速度对大文件时特别慢。能否把所有文件信息全部读入缓冲区,再处理。可是又如何保证每行每行地分析数据呢。

回答:

先使用Get语句将文件读到一个字符串中,然后,使用Split函数进行逐行的分解。之所以使用Get语句,而不使用Input函数,请参考QA000051 "VB 5提示错误:"输入超出文件尾""。下面是一个示例。
Private Sub Command1_Click()
Dim s As String
s = String(FileLen("c:\a.txt"), " ")
Open "c:\a.txt" For Binary As 1
Get #1, , s
Close 1
v = Split(s, vbCrLf)
Dim i
For i = 0 To UBound(v)
List1.AddItem v(i)
Next
End Sub

Public Function Split(ByVal sIn As String, Optional sDelim As _
String, Optional nLimit As Long = -1, Optional bCompare As _
VbCompareMethod = vbBinaryCompare) As Variant
Dim sRead As String, sOut() As String, nC As Integer
If sDelim = "" Then
Split = sIn
End If
sRead = ReadUntil(sIn, sDelim, bCompare)
Do
ReDim Preserve sOut(nC)
sOut(nC) = sRead
nC = nC + 1
If nLimit <> -1 And nC >= nLimit Then Exit Do
sRead = ReadUntil(sIn, sDelim)
Loop While InStr(1, sIn, sDelim, bCompare) > 0
ReDim Preserve sOut(nC)
sOut(nC) = sIn
Split = sOut
End Function


Public Function ReadUntil(ByRef sIn As String, _
sDelim As String, Optional bCompare As VbCompareMethod _
= vbBinaryCompare) As String
Dim nPos As String
nPos = InStr(1, sIn, sDelim, bCompare)
If nPos > 0 Then
ReadUntil = Left(sIn, nPos - 1)
sIn = Mid(sIn, nPos + Len(sDelim))
End If
End Function

 

Visual Basic 复制代码
Imports System

Public Class SplitTest
   
    Public Shared Sub Main()
        Dim words As String = "this is a list of words, with: a bit of punctuation."
        Dim split As String() = words.Split(New [Char]() {" "c, ","c, "."c, ":"c})
               
        Dim s As String
        For Each s In  split
            If s.Trim() <> "" Then
               
                Console.WriteLine(s)
            End If
        Next s
    End Sub 'Main
End Class 'SplitTest

Visual Basic(用法)
Dim instance As String
Dim separator As Char()
Dim returnValue As String()

returnValue = instance.Split(separator)

发布了661 篇原创文章 · 获赞 204 · 访问量 112万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览