Strings


 

Strings

  • a series of characters treated as a single unit.
  • may include letters, digits, and various special characters such as +, -, *, /, $, and others.
  • VB allows character strings up to 2 billion characters in length.
  • String literals are enclosed in double quotation marks such as: "CIS 220"
  • MSDN Reference
  • Strings are declared simply by using the String type name when you declare the variable. For instance:
Dim myVarString As String

String Functions

Len(string) -- determines the number of characters in a String. Returns an Integer value.

  • stringLength = Len( cityName )
  • Len returns 0 if there are no characters in the string. .

Comparing Strings

All characters are represented as numeric codes, and lexicographic comparison of two strings compares the numeric codes of the individual characters in the strings. 

The Unicode character set assigns a numeric value to every character.  For example, an "A" has the value 65, while "a" has the value 97. Subsequent characters increase in value, such as "b" which has a value of 98. See ASCII table.

String comparisons are performed on a character-by-character basis. 

Example: the String "Hello" is not equal to the String "hello".

Example: "zebra" < "zeus"

Strings can be compared using the standard relational (<, <=, >, >=) and equality (=, <>) operators.

════════════════════════════════

Strings can also be compared using the StrComp function.

StrComp(string1, string2[, compareMethod] )

                                  Return Values for StrComp

Return Value Comparison
-1
0
1
Null
string1 < string2
string1 = string2
string1 > string2
string1 or string2 is Null
  • StrComp(string1, string2) performs a case-sensitive comparison. 
  • StrComp(string1, string2, CompareMethod.Binary) performs a case-sensitive comparison.  
  • StrComp(string1, string2, CompareMethod.Text) performs a comparison that is not case-sensitive.

Notes: If the third argument is omitted, the comparison type defined in the option compare statement or project defaults is performed.

CompareMethod.Binary: "AAA" is less than "aaa".
CompareMethod.Text:    "AAA" is equal to "aaa".

Sample Code:

Dim myStr1, myStr2 As String
Dim myComp As Integer
myStr1 = "ABCD"
myStr2 = "abcd"

' The two strings sort equally. Returns 0
myComp = StrComp(myStr1, myStr2, CompareMethod.Text)

' myStr1 comes before myStr2. Returns -1.
myComp = StrComp(myStr1, myStr2, CompareMethod.Binary)


Locating Characters and Substrings in Strings

InStr -- returns the first position (Integer) of a string inside another string

  • position = InStr([StartPosition,] String, SubString, [, compareMethod])
  • returns 0 if substring is not found
  • StartPosition is a numeric expression that sets the start position for the search of SubString in String.  (The first character is position 1.)  If StartPosition is omitted, InStr begins searching at the first position.
  • String is the string being searched.
  • SubString is the string that is searched for in String.
  • compareMethod determines how to go about the comparison of the two strings.  If compareMethod is omitted, or if a value of CompareMethod.Binary is specified, InStr performs a case-sensitive comparison.  If a value of CompareMethod.Text is specified, the comparison will not be case sensitive.

' Checks to be sure name has been entered in Lastname, Firstname format
If InStr (txtName.Text, ",") = 0 Then
        lblMessage.Text = "Please separate names with a comma."
        txtName.Focus
Else
        name = txtName.Text
End If

InStr("papoose", "p")      ' returns 1
InStr("papoose", "poo")  ' returns 3

════════════════════════════════

InStrRev -- returns the first position (Integer) of a string inside another string, from the end of the string

  • position = InStrRev(String, SubString[, StartPosition]  [, compareMethod])
  • returns 0 if string is not found
  • String is the string being searched.
  • SubString is the string that is searched for in String.
  • StartPosition is a numeric expression that sets the start position for the search of SubString in String.   If StartPosition is omitted, InStrRev begins searching at the last character position.
  • compareMethod determines how to go about the comparison of the two strings.  If compareMethod is omitted, or if a value of CompareMethod.Binary is specified, InStrRev performs a case-sensitive comparison.  If a value of CompareMethod.Text is specified, the comparison will not be case sensitive.

InStrRev("papoose", "p")      ' returns 3


Extracting Substrings from Strings

Left -- returns a specified number of characters from the left-hand side of a String.

  • strResult = Left (String, Length)
  • strResult receives the return string
  • String is the string from which characters are being returned.
  • Length is the number of characters to be returned.  If Length = 0, then a zero-length string is returned.  If Length is greater than the length of the string, then the entire string is returned.
  • strResult = Microsoft.VisualBasic.Left("Hello World", 5) returns "Hello"

Right -- returns a specified number of characters from the right-hand side of a String.

  • strResult = Right (String, Length)
  • strResult receives the return string
  • String is the string from which characters are being returned.
  • Length is the number of characters to be returned.  If Length = 0, then a zero-length string is returned.  If Length is greater than the length of the string, then the entire string is returned.
  • strResult = Microsoft.VisualBasic.Right("Hello World", 5) returns "World"

Mid -- returns a specified number of characters from the any part of a String.

  • strResult = Mid (String, Start[,Length])
  • strResult receives the return string
  • String is the string from which characters are being returned.
  • Start is the character position in the string at which the string to be extracted begins.  If Start is greater than the number of characters in the string, Mid returns a zero-length string.
  • Length is the number of characters to be returned.  If this is omitted, or if there are fewer than Length characters in the text, then the entire string from Start onward is returned.
  • strResult = Mid("Hello World", 5, 3) returns "o W"
  • strResult = Mid("Hello World", 5) returns "o World"

exercise: Convert a name in the form Moose, Bullwinkle J. to Bullwinkle J. Moose.

Step 1: Locate the end of the last name

  • locate the comma using InStr function
  • commaLocation = InStr (name, ",")

Step 2: Extract first name and middle initial, if any

  • Starting in the location after the comma location, extract the remainder of the string using Mid.
  • firstName = Mid (name, commaLocation +1)

Step 3: Extract the Lastname

  • Starting at the beginning of the name, extract all characters up to the comma using Left.
  • lastName = Left (name, commaLocation - 1) 

Concatenating Strings

Strings can be combined through the process of concatenation.   Concatenation is performed by using the ampersand (&).  The plus sign (+) was used in previous releases of VB and should no longer be used.

    S1 = "Blue"
    S2 = "berry"
    S3 = S1 & S2

The above statement concatenates (or appends) S2 to the right of S1 to create an entirely new string, S3, containing "Blueberry."  S1 and S2 are unchanged.  

exercise: fullName = firstName & " " & lastName

Note:  You can also use the String.Concat method: fullname = String.Concat(firstName, lastName)


Case Conversion

UCase -- converts a String to all uppercase characters and returns a new String value. 

  • strResult = UCase(string)

LCase -- converts a String to all lowercase characters and returns a new String value. 

  • strResult = LCase(string)

Whitespace Removal

Trim -- returns a String that contains a copy of a given String with any leading and trailing spaces removed.

  • strResult = Trim(string)

LTrim -- returns a String that contains a copy of a given String with any leading spaces removed.

  • strResult = LTrim(string)

RTrim -- returns a String that contains a copy of a given String with any trailing spaces removed.

  • strResult = RTrim(string)

exercise: fullName = Trim (fullName)


Miscellaneous String Methods

Replace - finds and then replaces or removes occurrences of the "find" string within a target string.  

  • strResult = Replace ( targetString, findString, replaceString [, intStart] [, intCount] [,intCompareMethod])
  • strResult receives the string returned from the function
  • targetString is the string to be altered
  • findString is the string to be located in targetString
  • replaceString is the string that will replace findString once it is located
  • intStart is an optional position parameter within targetString at which to begin searching for findString
  • intCount is an optional parameter for the maximum number of times to replace findString in targetString.  If omitted, the default value is –1, which means make all possible substitutions.
  • intCompareMethod is an optional parameter that indicates case sensitivity for the replace.  CompareMethod.Binary is case sensitive, CompareMethod.Text is not.

-------------

strReverse -- reverses the order of a string. 

  • strResult = strReverse(origString)
  • strResult receives the string returned from the function
  • origString is the string to be reversed

Arrays of Strings

Split -- takes a list of words or numeric values stored in a string and places them into individual elements of an array of strings.

  • varResult = Split (strList[, strDelimiter][, intElemCnt][, CompareMethod])
  • varResult receives the array of strings returned from the function (a dynamic array is useful here)
  • strList is the string list that is to be separated 
  • strDelimiter is an optional parameter that specifies the character or string of characters used to identify the separate elements of the string.  Delimiters are used to find the end point of the current element and the starting point of the next element.  If a multiple character string is specified as the delimiter, then that entire string is assumed to be the delimiter, not each individual characters.  The delimiters are not returned with the substring.  The default value is the space character.
  • intElemCnt is an optional parameter that specifies the number of string array elements to create from strList
  • CompareMethod is an optional integer parameter that specifies case sensitivity for the delimiters
  • wordArray = Split ( stringOfWords )

-------------

Filter -- given an array of strings, produces a filtered array of strings by requiring or prohibiting specified values.

  • varResult = Filter (varList, strFind  [,boolInclude] [,CompareMethod])
  • varResult receives the string array returned
  • varList is the one-dimensional array of strings to be searched.
  • strFind is the string of characters used to determine which elements will be included in or excluded from the new array.
  • boolInclude is an optional Boolean flag that indicates whether to return substrings that include or exclude strFind. If boolInclude is True, the Filter function returns those items in the array that do contain strFind as a substring. If boolInclude is False, the Filter function returns those items in the array that do not contain strFind as a substring.
  • CompareMethod is an optional Integer argument that indicates case sensitivity when matching strFind to the varList.  The CompareMethod.Binary default forces a case-sensitive match.
  • Dim ctr As Integer
    Dim myStrings(2) As String
    myStrings(0) = "This"
    myStrings(1) = "Is"
    myStrings(2) = "It"

    Console.WriteLine("String array before filtering")
    For ctr = 0 To myStrings.GetUpperBound(0)
         Console.WriteLine(myStrings(ctr))
    Next
    Console.WriteLine()

    ' Returns ["This", "Is"].
    Dim subStrings() As String = Filter(myStrings, "is", True, CompareMethod.Text)

    Console.WriteLine("Non case sensitive (CompareMethod.Text) filter for ""is"" returning " _
           & "those that DO include substring (BooleanInclude=True)")
    For ctr = 0 To subStrings.GetUpperBound(0)
         Console.WriteLine(subStrings(ctr))
    Next
    Console.WriteLine()

    ' Returns ["This"].
    subStrings = Filter(myStrings, "is", True, CompareMethod.Binary)
    Console.WriteLine("Case sensitive (CompareMethod.Binary) filter for ""is"" returning " _
            & "those that DO include substring (BooleanInclude=True)")
    For ctr = 0 To subStrings.GetUpperBound(0)
         Console.WriteLine(subStrings(ctr))
    Next
    Console.WriteLine()

    ' Returns ["Is", "It"].
    subStrings = Filter(myStrings, "is", False, CompareMethod.Binary)
    Console.WriteLine("Case sensitive (CompareMethod.Binary) filter for ""is"" returning " _
            & "those that DO NOT include substring (BooleanInclude=False)")
    For ctr = 0 To subStrings.GetUpperBound(0)
         Console.WriteLine(subStrings(ctr))
    Next
  • String array before filtering
         This
         Is
         It

    Non case sensitive (CompareMethod.Text) filter for "is" returning those that DO include substring (BooleanInclude=True)
         This
         Is

    Case sensitive (CompareMethod.Binary) filter for "is" returning those that DO include substring (BooleanInclude=True)
         This

    Case sensitive (CompareMethod.Binary) filter for "is" returning those that DO NOT include substring (BooleanInclude=False)
         Is
         It

Practice exercise #1:

The Split function was not available in previous versions of VB.  Write a routine called getWord to accomplish the same task that Split accomplishes, namely parse a long string into individual words using the other string functions such as inStr, Left, Right, or Mid.  For additional practice, be sure that the words do not have any punctuation or whitespace characters attached, i.e., extract only the word.
Link

Practice exercise #2:

Write a function that returns a count of the number of words in a sentence like 

line = "        The old        dog, named       ""Peewee,"" ate a lot. Still, we all loved her...."


Link to String methods