You are on page 1of 45

.

PROCESSING
AND
EXPLORING TEXT FILES
COMPARING STRINGS

THREE WAYS TO COMPARE STRINGS


1. Using Comparison Operators (>, <, and =)
Performs character-by-character comparison of their
Unicode values

2. Using the Like Operator


Allows the use of wildcards, character lists, and
character ranges.

3. Using the String.Compare method of the String Class


Compares strings, ignoring or honoring their case, and
returns an integer that indicates their relative position in
the sort order (possible values: 1,0,-1)
COMPARING STRINGS

1. USING COMPARISON OPERATORS


Performs character-by-character comparison
of their ASCII values. (Uppercase letters have
LOWER ASCII value than lowercase. A longer
string has a GREATER value than a short string.
For other symbols, Refer to ASCII Table).
To compare without regard to capitalization,
put Option Compare Text on the namespace
area of the Code Editor
COMPARING STRINGS

1. USING COMPARISON OPERATORS


If strText1 < strText2 Then
In this case, VBA performs a character-by-character
comparison. The operators allow you to compare
String values based on their sort order

1. "73" < "9"


' The result of the preceding comparison is True.
2. "734" = "734"
' The result of the preceding comparison is True.
3. "aaa" > "aa“
' The result of the preceding comparison is True.
COMPARING STRINGS

2. USING THE LIKE OPERATOR


• The Like operator allows you to specify a pattern.
• The string is then compared against the pattern,
and if it matches, the result is True. Otherwise, the
result is False.
Characters in Pattern Matches in String
? Any single character
* Zero or more characters
# Any single digit (0-9)
[charlist] Any single character in charlist
[!charlist] Any single character NOT in charlist
COMPARING STRINGS

2. USING THE LIKE OPERATOR


Character lists (character_list) is a special notation for
matching any one of a group of characters. Within a
character list, you can specify a range of characters
(arranged in ascending order) by using the hyphen (-).
Range Matches
[ABC] "A" or "B" or "C"
[A-C] "A" or "B" or "C"
Any uppercase alphabetic
[A-Z]
character
Any upper- or lowercase
[A-Za-z]
alphabetic character
any character outside the range
[!H–L]
H–L
COMPARING STRINGS

2. USING THE LIKE OPERATOR

Examples:

Comparison Results
"ABC" Like "A?C" True
"A3C" Like "A#C" True
"ABC" Like "A??C" False
"A1z3C" Like "A*C" True
"1B3" Like "1[A-Z]3" True
"123" Like "1[!A-Z]3" True
COMPARING STRINGS

2. USING THE LIKE OPERATOR

Examples:

Comparison Results
"F" Like "FFF" False
"F" Like "f" False for Option Compare Binary
"F" Like "f" True for Option Compare Text
"aM5b" Like
True
"a[L-P]#[!c-e]"
"BAT123khg" Like
True
"B?T*"
COMPARING STRINGS

2. USING THE LIKE OPERATOR


Other Examples:
If strTemp Like “[A-Z] [A-Z] [A-Z] ###” Then
‘ You know that strTemp is a valid Phil. Plate no.
End If

If strTemp Like “[AEIOUaeiou]*” Then


‘ You know that the first character in strTemp is
a vowel
End If
COMPARING STRINGS

3. USING THE STRING.COMPARE METHOD


Syntax
ReturnVal = String.Compare(strA As String, StrB _
As String, IgnoreCase As Boolean)

Return Value:
0 if strA and strB is in the same row in a sort order
1 if strA precedes strB in the sort order
-1 if strA comes after strB in the sort order
COMPARING STRINGS

3. USING THE STRING.COMPARE METHOD


Dim str1 As String = "Singing"
Dim str2 As String = "SINGING"
Dim Match As Integer
Match = String.Compare(str1, str2, True)
'Match = 0 [strings match since case is ignored]
Match = String.Compare(str1, str2, False)
'Match = -1 [str2 precedes str1 in sort order]
Match = String.Compare(str2, str1, False)
'Match = 1 [str2 precedes str1 in sort order]
STRING MANIPULATION

 IMPORTANCE OF STRING MANIPULATION


1. Accessing and extracting data from a string
2. Data sorting
3. Formatting and comparing text

 TWO WAYS TO MANIPULATE STRINGS


1. String functions in a module called strings
2. Methods defined in the string class
THE STRINGS MODULE
Contains a set of functions that
can be used to manipulate strings
• Asc • Len
• AscW • LSet
THE STRING CLASS •

Chr
ChrW


LTrim
Mid
provides methods that • Filter • Replace
you can use to • Format • Right
• FormatCurrency • RSet
manipulate a string • FormatDateTime • RTrim
• FormatNumber • Space
• EndsWith • Substring • FormatPercent • Split
• IndexOf • ToLower • GetChar • StrComp
• Insert • ToUpper • InStr • StrConv
• Remove • Trim • InStrRev • StrDup
• Join • StrReverse
• Replace • TrimEnd
• LCase • Trim
• Split • TrimStart • Left • UCase
• StartsWith
THE STRING MODULE

SEARCH FXNS: CHR, CHRW AND JOIN


Chr and ChrW - Returns the character represented by the
code point. The valid range for Chr is 0 through 255, and
the valid range for ChrW is -32768 through 65535
'both returns 75 °C
Dim temp As String
temp = "75 " & Chr(176) & "C"
temp = "75 " & ChrW(176) & "C"
Join- Returns a string created by joining a number of
substrings contained in an array.
Dim Fruits() As String = {"Apple", "Banana", "Lemon"}
'returns "Apple, Banana, Lemon"
Dim favefruits As String = Join(Fruits, ", ")
'returns "Apple+Banana+Lemon"
Dim fruitshake As String = Join(Fruits, "+")
THE STRING MODULE

SEARCH FUNCTIONS: FILTER


Filter - Returns a zero-based array containing a subset of a String array
based on specified filter criteria.
Paramaters: (Source 1D Array, Criteria, IncludeMode, CompareMethod)

Dim TestStrings(2) As String


TestStrings(0) = "This"
TestStrings(1) = "Is"
TestStrings(2) = "It"
Dim subStrings() As String
' Returns ["This", "Is"].
subStrings = Filter(TestStrings, "is", True, CompareMethod.Text)
' Returns ["This"]. Include substring that exactly match
subStrings = Filter(TestStrings, "is", True, CompareMethod.Binary)
' Returns ["Is", "It"]. Include substring that does not match
subStrings = Filter(TestStrings, "is", False, CompareMethod.Binary)
THE STRING MODULE

SEARCH FUNCTIONS: SPACE


Lets you to create a string consisting only of spaces

SYNTAX:
strOut = Space(number of spaces)

Dim TestString As String


' Returns a string with 10 spaces.
TestString = Space(10)
' Inserts 10 spaces between the two strings.
TestString = "Hello" & Space(10) & "World"
THE STRING MODULE

SEARCH FUNCTIONS: LEN


Allows you to determine the length of any string or
string expression

SYNTAX:
lngCharCount = Len(strIn)

' Initializes variable.


Dim TestString As String = "Hello World"
' Returns 11.
Dim TestLen As Integer = Len(TestString)
THE STRING MODULE

SEARCH FXNS: INSTR AND INSTRREV

1. InStr Function
Can determine whether one string contains
another, and it can start looking at a specified
location in the string.

2. InstrRev Function
it searches strings similar to InStr function, except
that it searches from right to left. It is especially
used for finding file names on a path name.
THE STRING MODULE
SYNTAX: lngLocation = InStr([start], _
string1, string2 [,compare])

lngLocation = InstrRev(string1, _
string2 [,start] [,compare])

Start - a numeric expression that sets the starting


position for the search
string1 - the string expression being searched
string2 – the string expression being searched for
compare – either 0 or 1.
0 – performs a BINARY comparison
1 - performs a TEXT comparison
Return Value:
Character position where the first occurrence of string2
begins. Returns 0 – if string2 is not found in string1.
THE STRING MODULE

OPTION COMPARE STATEMENT


1. Binary (default)
Results in string comparisons based on a sort
order derived from the internal binary
representations of the characters.
A<B<E<Z<a<b<e<z<À<Ê<Ø<à<ê<ø
. < 0 < 1 < 2 < ... < 9 < A < B < ... < Z < a < b < ... < z
2. Text
Results in string comparisons based on a case-
insensitive text sort order determined by your
system's locale.
(A=a) < (À = à) < (B=b) < (E=e) < (Ê = ê) < (Z=z) < (Ø = ø)
THE STRING MODULE

INSTR FUNCTION

Assume that the strSent = “This is a test.”

Code Result
InStr(1,strSent,”is”) 3
InStr(4,strSent,”is”) 6
InStr(1,strSent,”IS”,0) 0
InStr(1,strSent,”IS”) 0
InStr(strSent,”IS”,1) 3
THE STRING MODULE

INSTRREV FUNCTION

Assume that the strPath =


“C:\WINNT\SYSTEM32\LOGFILES\LOGFILE.TXT”
12345678901234567890123456789012345678
0 1 2 3

Code Result
InstrRev(strPath,”\”) 27
InstrRev(strPath,”\”,26) 18
InstrRev(strSent,”\”,2) 0
THE STRING MODULE

WORKING WITH PORTIONS OF A STRING


returns one or more characters from a string
Syntax Purpose
Returns the leftmost length
Left(string,length) number of characters of the
string
Returns the rightmost length
Right(string,length) number of characters of the
string
 If used in a Windows Forms application, or any other class that
has a Left property, you must fully qualify the function with
Microsoft.VisualBasic.Left
THE STRING MODULE

SEARCH FUNCTIONS: LEFT AND RIGHT

Assume that the strProgName = “Visual Basic”

Code Result

Microsoft.VisualBasic.Left(strProgName, 3) Vis
Microsoft.VisualBasic.Right(strProgName, 2) ic
Microsoft.VisualBasic.Left(strProgName, 6) Visual
Microsoft.VisualBasic.Right (strProgName, 5) Basic
Microsoft.VisualBasic.Left(strProgName, 8) Visual B
THE STRING MODULE

MID AS A “FUNCTION”

returns length number of characters from a


string, beginning at position “start”

Syntax
Mid(string,start [,length])

Note: If length is omitted, the function


returns all characters from the start
position up to the end of the string
THE STRING MODULE

MID AS A “FUNCTION”
Assume that the strProgName = “Visual Basic”

Code Result
Mid(strProgName, 2,1) i

Mid(strProgName, 4) ual Basic

Mid(strProgName, 4,2) ua

Mid(strProgName, 8,3) Bas

Mid(strProgName, 8) Basic
THE STRING MODULE

MID AS A “STATEMENT”

Replaces a specified number of characters in


a String variable with characters from another
string.

Syntax

Mid(ByRef Target As String, ByVal Start As


Integer, Optional ByVal Length As Integer)
= StringExpression
THE STRING MODULE

MID AS A “STATEMENT”
Example :
This example uses the Mid statement to replace a
specified number of characters in a string variable with
characters from another string.
Dim TestString As String
' Initializes string.
TestString = "The dog jumps"
' Returns "The fox jumps".
Mid(TestString, 5, 3) = "fox"
' Returns "The cow jumps".
Mid(TestString, 5) = "cow"
' Returns "The cow jumpe".
Mid(TestString, 5) = "cow jumped over"
' Returns "The duc jumps".
Mid(TestString, 5, 3) = "duck"
THE STRING MODULE

MID: STATEMENT VS FUNCTION

Dim strExample As String = “This is an example.”


Dim intResult As Integer

Mid Statement Mid Function


Mid (strExample, 1, 4) intResult = Mid
Expression = “That” (strExample, 1, 4)

Result “That is an example.” “This”


THE STRING CLASS

SUBSTRING
Returns a fixed number of characters in a string
from a given starting point.

(Note: The first element in a string has an index of 0.)


Example
Dim AllText = "Visual Basic 2010"
Dim partialString As String
partialString = AllText.Substring(7, 5)
THE STRING CLASS

SPLIT
Splits a string into substrings based on a specified
separator and puts the substring in an array.

Example No.1
Dim AllText As String = "Visual Basic 2010"
Dim SplitText() As String
SplitText = AllText.Split(" ")
THE STRING CLASS

SPLIT
Example No.2
Dim AllText As String = _
"This is a sentence. This is a sentence too."
Dim SplitText() As String
SplitText = AllText.Split(".")
THE STRING CLASS

TOLOWER AND TOUPPER


ToUpper – transforms the string to UpperCase
ToLower – transforms the String to LowerCase
Example
Dim oldString = "I Am a StRinG"
Dim LowCase As String = oldString.ToLower
Dim UpCase As String = oldString.ToUpper
THE STRING CLASS

REPLACE
Replaces all instances of a substring in a string
with another string.
Example
Dim baseString = "Visual Basic *"
Dim newString As String = baseString.Replace("*", "2010")
Dim newString2 As String = _
newString.Replace("Basic", "Studio")
THE STRING CLASS

REPLACE
Dim base = txtBase.Text
Dim displayText As String = "The * equivalent of 10 is ?"
Dim baseText As String = ""

If base = 2 Then
baseText = "binary"
ElseIf base = 8 Then
baseText = "octal"
Else
baseText = "Base " & base.ToString
End If

displayText = displayText.Replace("*", baseText)


displayText = displayText.Replace("?", ans)
THE STRING CLASS

STRING.REPLACE(OLDVALUE,NEWVALUE)
oldValue - The string to be replaced.
newValue - The string to replace ALL occurrences of
oldValue.
Return Value - A string that is equivalent to the current
string except that all instances of oldValue are replaced
with newValue. If oldValue is not found in the current
instance, the method returns the current instance
unchanged. If newValue is null, all occurrences of
oldValue are removed. Because this method returns the
modified string, you can chain together successive calls to
the Replace method to perform multiple replacements on
the original string.
Example
Dim s As String = "aaa"
s = s.Replace("a", "b").Replace("b", "c").Replace("c", "d")
' The final string: 'ddd‘
THE STRING CLASS

INDEXOF
Finds the index starting point of one string within a
larger string.

Example
Dim baseString = "Visual Basic"
Dim i1 As Byte = baseString.IndexOf("i")
Dim i2 As Byte = baseString.IndexOf("i",2)
THE STRING CLASS

STRING.INDEXOF(VALUE)
Return Value - The zero-based index position of
value if that string is found, or -1 if it is not. If value
is String.Empty, the return value is 0.

Example
Dim str As String = "animal"
Dim index As Integer = str.IndexOf("n")

'return value is 1
THE STRING CLASS

REMOVE
Removes characters from the middle of a
string.
Example
Dim RawStr, CleanStr As String
RawStr = "Hello333 there"
CleanStr = RawStr.Remove(5, 3)
STRING.REMOVE(STARTINDEX)
Returns a new string in which all the characters in the current
instance, beginning at a specified position and continuing
through the last position, have been deleted.
startIndex - The zero-based position to begin deleting
characters.
Return Value - A new string that is equivalent to this string
except for the removed characters.

Example
Dim s As String = "abc---def“
Console.WriteLine("Index: 012345678") 'Index: 012345678
Console.WriteLine("1) {0}", s) '1) abc---def
Console.WriteLine("2) {0}", s.Remove(3)) '2) abc
Console.WriteLine("3) {0}", s.Remove(3, 3)) '3) abcdef
THE STRING CLASS

INSERT
Adds characters to the middle of a string.
Dim base = 2
Dim displayText As String = "The equivalent of 10 is 1010"
Dim baseText As String = ""

If base = 2 Then baseText = " binary "


displayText = displayText.Insert(4, baseText)
THE STRING CLASS

STRING.INSERT(STARTINDEX,VALUE)
startIndex - The zero-based index position of the
insertion.
Value - The string to insert.
Return Value - A new string that is equivalent to this
instance, but with value inserted at position startIndex.
If startIndex is equal to the length of this instance,
value is appended to the end of this instance.

Example
Dim original As String = "aaabbb"
Dim modified As Integer = original.Insert(3, " ")

'The original string: 'aaabbb'


‘The modified string: 'aaa bbb'
THE STRING CLASS

STRING.INSERT(STARTINDEX,VALUE)
startIndex - The zero-based index position of the
insertion.
Value - The string to insert.
Return Value - A new string that is equivalent to this
instance, but with value inserted at position startIndex.
If startIndex is equal to the length of this instance,
value is appended to the end of this instance.

Example
"abc".Insert(2, "XYZ") becomes "abXYZc"
"abc".Insert(2, "XYZ") becomes "abXYZc"

'The original string: 'aaabbb'


‘The modified string: 'aaa bbb'
THE STRING CLASS

STARTSWITH AND ENDSWITH


StartsWith - Determines whether a string starts with a
specified string.
EndsWith - Determines whether a string ends with a
specified string.
Example
Dim baseString = "Visual Basic"
Dim result1 As Boolean = baseString.StartsWith("Visual")
Dim result2 As Boolean = baseString.EndsWith("Basic")
THE STRING CLASS

TRIM, TRIMSTART, TRIMEND


Trim - Removes leading and following spaces from a string.
TrimStart – Removes all the leading white spaces (or set of
characters from a string array) from a string
TrimEnd – Removes all trailing white spaces (or set of
characters from a string array) from a string
Example
Dim RawStr, CleanStr, CleanStart, CleanEnd As String
RawStr = " Hello there "
CleanStr = RawStr.Trim
CleanStart = RawStr.TrimStart
CleanEnd = RawStr.TrimEnd

You might also like