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 Properties
String.Length -- determines the number of
characters in a String. Returns
an Integer value.
- stringLength = cityName.Length
-
Length returns 0 if there
are no characters in the string.
.
String Methods
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
String.Compare
method.
String.Compare (String, String)
or
String.Compare (String, String,
Boolean)
Return Values for Compare
| Return Value |
Comparison |
< 0
0
> 0 |
string1 < string2
string1 = string2
string1 > string2 |
- String.Compare (string1,
string2)
- performs a case-sensitive
comparison.
-
String.Compare (string1, string2,
False)
- performs a case-sensitive
comparison.
-
String.Compare (string1, string2,
True)
- performs a comparison that is not
case-sensitive.
Sample Code:
Dim myStr1, myStr2 As String
Dim myComp As Integer
myStr1 = "ABCD"
myStr2 = "abcd"
' The two strings sort equally.
Returns 0
myComp = String.Compare(myStr1, myStr2, True)
' myStr1 comes before myStr2.
Returns -1.
myComp = String.Compare(myStr1, myStr2, False)
Locating Characters and Substrings
in Strings
String.IndexOf
-- returns
the first position (Integer) of a string inside another string
- position =
String.IndexOf
( SubString [, StartPosition])
- returns -1 if substring 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.
(Index numbering
starts from zero.) If
StartPosition
is omitted, IndexOf
begins searching at the first position.
- The search for
SubString
is case-sensitive.
' Checks to be sure name has been
entered in Lastname, Firstname format
tempName = txtName.Text
If tempName.IndexOf(",")
= 0 Then
lblMessage.Text = "Please
separate names with a comma."
txtName.Focus
Else
name = tempName
End If
testString = "papoose"
testString.IndexOf("p") ' returns 0
testString.IndexOf("poo") ' returns 2
Extracting Substrings from Strings
String.Substring
-- returns a specified number of characters from the any part of a String.
-
strResult =
String.Substring (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.
Start is zero-based.
- Length
is the number of characters to be returned. If this is omitted then the
entire string from
Start
onward is returned.
- testString = "Hello
World")
- strResult = testString.Substring (4, 3) returns "o W"
- strResult =
testString.Substring (4) 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 IndexOf function
- commaLocation = name.IndexOf(",")
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 =
name.Substring (commaLocation +1)
Step 3: Extract the
Lastname
- Starting at the beginning of
the name, extract all characters up to the comma using
Left.
- lastName = name.Substring (0, 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
You can also use the
String.Concat method:
fullname = String.Concat(firstName,
" ",
lastName)
Case Conversion
String.ToUpper
-- converts a
String
to all uppercase characters and returns a new
String
value.
- strResult = testString.ToUpper()
String.ToLower
-- converts a
String
to all lowercase characters and returns a new
String
value.
- strResult = testString.ToLower()
Whitespace Removal
String.Trim
-- returns a
String
that contains a copy of a given
String
with any leading and trailing spaces removed.
- strResult = testString.Trim()
String.TrimStart
-- returns a String
that contains a copy of a given
String
with any leading spaces removed.
- strResult = testString.TrimStart()
String.TrimEnd
-- returns a
String
that contains a copy of a given
String
with any trailing spaces removed.
- strResult = testString.TrimEnd()
exercise:
fullName = fullName.Trim()
The Trim methods can also be used to remove all
occurrences of a set of specified characters from the beginning and end of a
string.
Dim str1 As [String] =
"*;|@123***456@|;*"
Dim delim As [String] = "|*;@"
Dim str2 As [String] = str1.Trim(delim.ToCharArray() ' is set to
"123***456"
Miscellaneous
String
Methods
String.Replace
- finds and then replaces or removes occurrences of the "find" string
within a target string.
- strResult = targetString.Replace (
oldValue, newValue )
- strResult
receives the string returned from the function
- targetString
is the string to be altered
- oldValue
is the string to be replaced in
targetString
- newValue
is the string to replace all occurrences of
oldValue.
-------------
String.Insert --
inserts a specified instance of a string at a
specified index position in this instance.
- strResult =
origString.Insert(startIndex, insertString)
- strResult
receives the string returned from the method
- origString
is the string to be accept inserts
- startIndex is the
index position of the insertion.
- insertString is
the string to be inserted.
-------------
String.Remove --
removes a specified instance of a string
beginning at a specified index position in this instance.
- strResult =
origString.Remove(startIndex, numChars)
- strResult
receives the string returned from the method
- origString
is the string to be accept inserts
- startIndex is the
index position of the insertion.
- numChars
is the number of characters to be deleted.
-------------
String.Copy
-- creates a new instance of String with the
same value as a specified String.
- strResult =
String.Copy(origString)
- strResult
receives the string returned from the method
- origString
is the string to be copied
- Dim str1 As String = "abc"
Dim str2 As String = "xyz"
Console.WriteLine("1) str1 = " & str1) ' writes abc
Console.WriteLine("2) str2 = " & str2) ' writes xyz
Console.WriteLine("Copy...")
str2 = String.Copy(str1)
Console.WriteLine("3) str1 = '{0}'", str1) ' writes abc
Console.WriteLine("4) str2 = '{0}'", str2) ' writes abc
Arrays of Strings
String.Split --
Identifies the
substrings in a string that are delimited by one or more characters specified in
an array, then places the substrings into a String array.
- varResult = String.Split (charSeparatorArray() [, intElemCnt])
- varResult
receives the array of strings returned from the method (a dynamic array is
useful here)
- String
is the string list that is to be separated
- charSeparatorArray()
is an An array of Unicode characters that delimit the substrings in this
instance.
- intElemCnt
is an optional parameter that specifies the number of string array elements
to create from strList.
- wordArray = stringOfWords.Split (
" " )
- Dim delimStr As String =
" ,.:"
Dim delimiter As Char() = delimStr.ToCharArray()
Dim wordList As String = "one two,three:four."
Dim split As String() = Nothing
Console.WriteLine("The delimiters are -{0}-", delimStr)
Dim ctr As Integer
For ctr = 1 To 5
split = wordList.Split(delimiter, ctr)
Console.WriteLine(ControlChars.Cr + "count = {0,2} ..............", ctr)
Dim stringElt As String
For Each stringElt In split
Console.WriteLine("-{0}-", stringElt)
Next stringElt
Next ctr
- The delimiters are - ,.:-
count = 1 ..............
-one two,three:four.-
count = 2 ..............
-one-
-two,three:four.-
count = 3 ..............
-one-
-two-
-three:four.-
count = 4 ..............
-one-
-two-
-three-
-four.-
count = 5 ..............
-one-
-two-
-three-
-four-
--
Practice exercise #1:
The
Split
method 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
IndexOf
and
Substring.
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...."
Tutorial
MS Link
|