-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathVBALib_StringUtils.bas
86 lines (75 loc) · 2.78 KB
/
VBALib_StringUtils.bas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
Attribute VB_Name = "VBALib_StringUtils"
' Common VBA Library - StringUtils
' Provides useful functions for manipulating strings.
Option Explicit
' Determines whether a string starts with a given prefix.
Public Function StartsWith(s As String, prefix As String, _
Optional caseSensitive As Boolean = True) As Boolean
If caseSensitive Then
StartsWith = (Left(s, Len(prefix)) = prefix)
Else
StartsWith = (Left(LCase(s), Len(prefix)) = LCase(prefix))
End If
End Function
' Determines whether a string ends with a given suffix.
Public Function EndsWith(s As String, suffix As String, _
Optional caseSensitive As Boolean = True) As Boolean
If caseSensitive Then
EndsWith = (Right(s, Len(suffix)) = suffix)
Else
EndsWith = (Right(LCase(s), Len(suffix)) = LCase(suffix))
End If
End Function
' Splits a string on a given delimiter, trimming trailing and leading
' whitespace from each piece of the string.
Public Function SplitTrim(s As String, delim As String) As String()
Dim arr() As String
arr = Split(s, delim)
Dim i As Integer
For i = 0 To UBound(arr)
arr(i) = Trim(arr(i))
Next
SplitTrim = arr
End Function
' Trims a specified set of characters from the beginning and end
' of the given string.
' @param toTrim: The characters to trim. For example, if ",; "
' is given, then all spaces, commas, and semicolons will be removed
' from the beginning and end of the given string.
Public Function TrimChars(s As String, toTrim As String)
TrimChars = TrimTrailingChars(TrimLeadingChars(s, toTrim), toTrim)
End Function
' Trims a specified set of characters from the beginning of the
' given string.
' @param toTrim: The characters to trim. For example, if ",; "
' is given, then all spaces, commas, and semicolons will be removed
' from the beginning of the given string.
Public Function TrimLeadingChars(s As String, toTrim As String)
If s = "" Then
TrimLeadingChars = ""
Exit Function
End If
Dim i As Integer
i = 1
While InStr(toTrim, Mid(s, i, 1)) > 0 And i <= Len(s)
i = i + 1
Wend
TrimLeadingChars = Mid(s, i)
End Function
' Trims a specified set of characters from the end of the given
' string.
' @param toTrim: The characters to trim. For example, if ",; "
' is given, then all spaces, commas, and semicolons will be removed
' from the end of the given string.
Public Function TrimTrailingChars(s As String, toTrim As String)
If s = "" Then
TrimTrailingChars = ""
Exit Function
End If
Dim i As Integer
i = Len(s)
While InStr(toTrim, Mid(s, i, 1)) > 0 And i >= 1
i = i - 1
Wend
TrimTrailingChars = Left(s, i)
End Function