分解一个字符串也就是从字符串中按照一定的位置抽取一些子部分或者一个分隔符。需要分解字符串的原因包括:当使用一个命令行变量和读取CSV文件的时候。在本文中,我们将提供一个能够满足字符串分解需要的VB函数。
在表面上,基于一个分隔符的字符串分解操作看起来非常简单。例如,字符串"a,b,c"很容易被分解为三个子字符串"a","b",以及"c",这都是采用逗号作为分隔符。但是,事实上并不是那么简单。举个例子,字符串"a,,b,c"应该被分解为四个子字符串,因为双个逗号表示的是一个缺少(或空白)的子字符。同样的,字符串",a,b,c"的最前面逗号表示的是一个缺少或者空白的子字符。所以,任何一个字符串分解函数都必须能够将一个缺少或者空白的字符包含在计算当中。
另一个需求就是使用多字符作为一个分隔符。在某些程序中,需要在数据中包含一些字符。例如,使用一个符号作为一个分隔工作终点,但数据本身不能包含这一字符。你可以使用而达到你的要求。
函数ParseString()能够满足这些所有的需求。这一函数传递两个变量:被分解的字符以及分隔字符串。它返回的是一个包含子字符的一个数组。当出现错误的情况(在代码的注解中会得到解释),函数返回Null。这一调用函数可以先使用IsNull来校验函数是否返回的是Null,然后函数就使用UBound()来确定返回的数组的大小,接着访问分解的子字符。
Public Function ParseString(StringToParse As String,
Delim As String) As
Variant
' Returns an array containing the results of parsing
' a string based on the specified delimiter.
' If StringToParse or Delim is empty returns Null
' If Len(Delim) >= Len(StringToParse returns Null
' If StringToParse does not contain the delimiter, returns
' the entire string.
Dim a() As String
Dim s As String
Dim DelimPos As Integer
Dim count As Integer
If Len(StringToParse) = 0 Or Len(Delim) = 0 Then
ParseString = Null
Exit Function
End If
If Len(Delim) >= Len(StringToParse) Then
ParseString = Null
Exit Function
End If
DelimPos = InStr(1, StringToParse, Delim)
If DelimPos = 0 Then
ReDim a(0)
a(0) = StringToParse
ParseString = a
Exit Function
End If
s = StringToParse
count = 0
Do
ReDim Preserve a(count)
a(count) = Left(s, DelimPos - 1)
s = Right(s, Len(s) - (DelimPos + Len(Delim) - 1))
count = count + 1
DelimPos = InStr(1, s, Delim)
If DelimPos = 0 Then
ReDim Preserve a(count)
a(count) = s
s = ""
End If
Loop Until Len(s) = 0
ParseString = a
End Function
本文作者Peter Aitken:自从Visual Basic 1.0版以来,Peter Aitken就一直使用VB编程。他已经编写过很多关于VisualBasic以及其他计算机和编程的书以及杂志文章了。
责任编辑:炒饭