Strings in VB-NET
Strings in VB-NET
This section describes the basic concepts behind using strings in Visual Basic.
In This Section
Introduction to Strings in Visual Basic
Lists topics that describe the basic concepts behind using strings in Visual Basic.
See also
Visual Basic Language Features
Introduction to Strings in Visual Basic
Article • 09/15/2021
This section describes the basic concepts behind using strings in Visual Basic.
In This Section
String Basics
Introduces the basic concepts behind using strings and string variables.
See also
Strings
String Basics in Visual Basic
Article • 09/15/2021
The String data type represents a series of characters (each representing in turn an
instance of the Char data type). This topic introduces the basic concepts of strings in
Visual Basic.
String Variables
An instance of a string can be assigned a literal value that represents a series of
characters. For example:
VB
A String variable can also accept any expression that evaluates to a string. Examples
are shown below:
VB
Any literal that is assigned to a String variable must be enclosed in quotation marks
(""). This means that a quotation mark within a string cannot be represented by a
quotation mark. For example, the following code causes a compiler error:
VB
VB
In the preceding example, the two quotation marks preceding the word Look become
one quotation mark in the string. The three quotation marks at the end of the line
represent one quotation mark in the string and the string termination character.
VB
Dim x = "hello
world"
The resulting string contains newline sequences that you used in your string literal (vbcr,
vbcrlf, etc.). You no longer need to use the old workaround:
VB
Dim x = <xml><![CDATA[Hello
World]]></xml>.Value
Characters in Strings
A string can be thought of as a series of Char values, and the String type has built-in
functions that allow you to perform many manipulations on a string that resemble the
manipulations allowed by arrays. Like all array in .NET Framework, these are zero-based
arrays. You may refer to a specific character in a string through the Chars property,
which provides a way to access a character by the position in which it appears in the
string. For example:
VB
In the above example, the Chars property of the string returns the fourth character in
the string, which is D , and assigns it to myChar . You can also get the length of a
particular string through the Length property. If you need to perform multiple array-
type manipulations on a string, you can convert it to an array of Char instances using
the ToCharArray function of the string. For example:
VB
The variable myArray now contains an array of Char values, each representing a
character from myString .
VB
Here, a string variable is created, given a value, and then its value is changed.
More specifically, in the first line, an instance of type String is created and given the
value This string is immutable . In the second line of the example, a new instance is
created and given the value Or is it? , and the string variable discards its reference to
the first instance and stores a reference to the new instance.
Unlike other intrinsic data types, String is a reference type. When a variable of
reference type is passed as an argument to a function or subroutine, a reference to the
memory address where the data is stored is passed instead of the actual value of the
string. So in the previous example, the name of the variable remains the same, but it
points to a new and different instance of the String class, which holds the new value.
See also
Introduction to Strings in Visual Basic
String Data Type
Char Data Type
Basic String Operations
Types of String Manipulation Methods
in Visual Basic
Article • 09/15/2021
There are several different ways to analyze and manipulate your strings. Some of the
methods are a part of the Visual Basic language, and others are inherent in the String
class.
VB
In this example, the Mid function performs a direct operation on aString and assigns
the value to bString .
For a list of Visual Basic string manipulation methods, see String Manipulation Summary.
Shared Methods
A shared method is a method that stems from the String class itself and does not
require an instance of that class to work. These methods can be qualified with the name
of the class ( String ) rather than with an instance of the String class. For example:
VB
Instance Methods
Instance methods, by contrast, stem from a particular instance of String and must be
qualified with the instance name. For example:
VB
In this example, the String.Substring method is a method of the instance of String (that
is, aString ). It performs an operation on aString and assigns that value to bString .
For more information, see the documentation for the String class.
See also
Introduction to Strings in Visual Basic
Nothing and Strings in Visual Basic
Article • 09/15/2021
The Visual Basic runtime and the .NET Framework evaluate Nothing differently when it
comes to strings.
VB
' stringLength = 0
stringLength = Len(MyString)
The Visual Basic runtime usually evaluates Nothing as an empty string (""). The .NET
Framework does not, however, and throws an exception whenever an attempt is made
to perform a string operation on Nothing .
See also
Introduction to Strings in Visual Basic
How Culture Affects Strings in Visual
Basic
Article • 09/15/2021
This Help page discusses how Visual Basic uses culture information to perform string
conversions and comparisons.
For example, if your application asks users to enter a date as a string, it should expect
users to format the strings according to their culture, and the application should convert
the string appropriately. If your application then presents that date in its user interface,
it should present it in the user's culture.
However, if the application uploads the date to a central server, it should format the
string according to one specific culture, to prevent confusion between potentially
different date formats.
Culture-Sensitive Functions
All of the Visual Basic string-conversion functions (except for the Str and Val functions)
use the application's culture information to make sure that the conversions and
comparisons are appropriate for the culture of the application's user.
The Str (converts numbers to strings) and Val (converts strings to numbers) functions
do not use the application's culture information when converting between strings and
numbers. Instead, they recognize only the period (.) as a valid decimal separator. The
culturally-aware analogues of these functions are:
Conversions that use the current culture. The CStr and Format functions convert
a number to a string, and the CDbl and CInt functions convert a string to a
number.
When you need to perform a string conversion in a specific culture format, you should
use the CultureInfo class that is built into the .NET Framework. You can create a new
CultureInfo object for a specific culture by passing the culture's name to the
CultureInfo constructor. The supported culture names are listed in the CultureInfo class
Help page.
Alternatively, you can get an instance of the invariant culture from the
CultureInfo.InvariantCulture property. The invariant culture is based on the English
culture, but there are some differences. For example, the invariant culture specifies a 24-
hour clock instead of a 12-hour clock.
To convert a date to the culture's string, pass the CultureInfo object to the date object's
ToString(IFormatProvider) method. For example, the following code displays
"07/04/2005 00:00:00", regardless of the application's culture settings.
VB
Comparing Strings
There are two important situations where string comparisons are needed:
Sorting data for display to the user. Use operations based on the current culture
so the strings sort appropriately.
You can perform both types of comparisons with the Visual Basic StrComp function.
Specify the optional Compare argument to control the type of comparison: Text for
most input and output Binary for determining exact matches.
The StrComp function returns an integer that indicates the relationship between the two
compared strings based on the sorting order. A positive value for the result indicates
that the first string is greater than the second string. A negative result indicates the first
string is smaller, and zero indicates equality between the strings.
VB
You can also use the .NET Framework partner of the StrComp function, the
String.Compare method. This is a static, overloaded method of the base string class. The
following example illustrates how this method is used:
VB
For finer control over how the comparisons are performed, you can use additional
overloads of the Compare method. With the String.Compare method, you can use the
comparisonType argument to specify which type of comparison to use.
Security Considerations
If your application makes security decisions based on the result of a comparison or
case-change operation, then the operation should use the String.Compare method, and
pass Ordinal or OrdinalIgnoreCase for the comparisonType argument.
See also
CultureInfo
Introduction to Strings in Visual Basic
Type Conversion Functions
Interpolated Strings (Visual Basic
Reference)
Article • 08/05/2022
Used to construct strings. An interpolated string looks like a template string that
contains interpolated expressions. An interpolated string returns a string that replaces
the interpolated expressions that it contains with their string representations. This
feature is available in Visual Basic 14 and later versions.
VB
VB
VB
where:
field-width is a signed integer that indicates the number of characters in the field. If
it is positive, the field is right-aligned; if negative, left-aligned.
format-string is a format string appropriate for the type of object being formatted.
For example, for a DateTime value, it could be a standard date and time format
string such as "D" or "d".
) Important
You cannot have any white space between the $ and the " that starts the string.
Doing so causes a compiler error.
You can use an interpolated string anywhere you can use a string literal. The
interpolated string is evaluated each time the code with the interpolated string executes.
This allows you to separate the definition and evaluation of an interpolated string.
To include a curly brace ("{" or "}") in an interpolated string, use two curly braces, "{{" or
"}}". See the Implicit Conversions section for more details.
VB
Implicit Conversions
There are three implicit type conversions from an interpolated string:
VB
Public Module Example
Public Sub Main()
Dim name = "Bartholomew"
Dim s1 = $"Hello, {name}!"
Console.WriteLine(s1)
End Sub
End Module
' The example displays the following output:
' Hello, Bartholomew!
' </Snippet1>
This is the final result of a string interpretation. All occurrences of double curly
braces ("{{" and "}}") are converted to a single curly brace.
The following example uses reflection to display the members as well as the field
and property values of an IFormattable variable that is created from an
interpolated string. It also passes the IFormattable variable to the
Console.WriteLine(String) method.
VB
Imports System.Globalization
Imports System.Reflection
Note that the interpolated string can be inspected only by using reflection. If it is
passed to a string formatting method, such as WriteLine(String), its format items
are resolved and the result string returned.
All occurrences of double curly braces ("{{" and "}}") remain as double curly braces
until you format. All contained interpolation expressions are converted to {0}, {1},
and so on.
VB
Imports System.Globalization
See also
System.IFormattable
System.FormattableString
Visual Basic Language Reference
Zero-based vs. One-based String Access
in Visual Basic
Article • 09/15/2021
This topic compares how Visual Basic and the .NET Framework provide access to the
characters in a string. The .NET Framework always provides zero-based access to the
characters in a string, whereas Visual Basic provides zero-based and one-based access,
depending on the function.
One-Based
For an example of a one-based Visual Basic function, consider the Mid function. It takes
an argument that indicates the character position at which the substring will start,
starting with position 1. The .NET Framework String.Substring method takes an index of
the character in the string at which the substring is to start, starting with position 0.
Thus, if you have a string "ABCDE", the individual characters are numbered 1,2,3,4,5 for
use with the Mid function, but 0,1,2,3,4 for use with the String.Substring method.
Zero-Based
For an example of a zero-based Visual Basic function, consider the Split function. It
splits a string and returns an array containing the substrings. The .NET Framework
String.Split method also splits a string and returns an array containing the substrings.
Because the Split function and Split method return .NET Framework arrays, they must
be zero-based.
See also
Mid
Split
Substring
Split
Introduction to Strings in Visual Basic
How to: create strings using a
StringBuilder in Visual Basic
Article • 09/15/2021
This example constructs a long string from many smaller strings using the StringBuilder
class. The StringBuilder class is more efficient than the &= operator for concatenating
many strings.
Example
The following example creates an instance of the StringBuilder class, appends 1,000
strings to that instance, and then returns its string representation:
VB
See also
Using the StringBuilder Class
&= Operator
Strings
Creating New Strings
Manipulating Strings
How to: search within a string (Visual
Basic)
Article • 09/15/2021
This article shows an example of how to search within a string in Visual Basic.
Example
This example calls the IndexOf method on a String object to report the index of the first
occurrence of a substring:
VB
Robust programming
The IndexOf method returns the location of the first character of the first occurrence of
the substring. The index is 0-based, which means the first character of a string has an
index of 0.
For optimal error control, you might want to enclose the string search in the Try block
of a Try...Catch...Finally Statement construction.
See also
IndexOf
Try...Catch...Finally Statement
Introduction to Strings in Visual Basic
Strings
Converting between strings and other
data types in Visual Basic
Article • 09/15/2021
This section describes how to convert strings into other data types.
In This Section
How to: Convert an Array of Bytes into a String in Visual Basic
How to convert the bytes from a byte array into a string.
This topic shows how to convert the bytes from a byte array into a string.
Example
This example uses the GetString method of the Encoding.Unicode encoding class to
convert all the bytes from a byte array into a string.
VB
Return System.Text.Encoding.Unicode.GetString(bytes)
End Function
You can choose from several encoding options to convert a byte array into a string:
Encoding.Default: Gets an encoding for the system's current ANSI code page.
Encoding.Unicode: Gets an encoding for the UTF-16 format using the little-endian
byte order.
Encoding.UTF32: Gets an encoding for the UTF-32 format using the little-endian
byte order.
See also
System.Text.Encoding
GetString
How to: Convert Strings into an Array of Bytes in Visual Basic
How to: Convert Strings into an Array of
Bytes in Visual Basic
Article • 09/15/2021
Example
This example uses the GetBytes method of the Encoding.Unicode encoding class to
convert a string into an array of bytes.
VB
Return System.Text.Encoding.Unicode.GetBytes(str)
End Function
You can choose from several encoding options to convert a string into a byte array:
Encoding.Default: Gets an encoding for the system's current ANSI code page.
Encoding.Unicode: Gets an encoding for the UTF-16 format using the little-endian
byte order.
Encoding.UTF32: Gets an encoding for the UTF-32 format using the little-endian
byte order.
See also
System.Text.Encoding
GetBytes
How to: Convert an Array of Bytes into a String in Visual Basic
How to: Create a String from An Array
of Char Values (Visual Basic)
Article • 09/15/2021
Example
VB
The syntax "a"c , where a single c follows a single character in quotation marks, is used
to create a character literal.
Robust Programming
Null characters (equivalent to Chr(0) ) in the string lead to unexpected results when
using the string. The null character will be included with the string, but characters
following the null character will not be displayed in some situations.
See also
String
Char Data Type
Data Types
How to: Convert Hexadecimal Strings to
Numbers (Visual Basic)
Article • 09/15/2021
The first argument of the ToInt32(String, Int32) method is the string to convert. The
second argument describes what base the number is expressed in; hexadecimal is
base 16.
VB
If the prefix or a digit separator is present, the call to the ToInt32(String, Int32)
method throws a FormatException.
See also
Hex
Convert.ToInt32
How to: Convert a String to an Array of
Characters in Visual Basic
Article • 09/15/2021
Sometimes it is useful to have data about the characters in your string and the positions
of those characters within your string, such as when you are parsing a string. This
example shows how you can get an array of the characters in a string by calling the
string's ToCharArray method.
Example 1
This example demonstrates how to split a string into a Char array, and how to split a
string into a String array of its Unicode text characters. The reason for this distinction is
that Unicode text characters can be composed of two or more Char characters (such as
a surrogate pair or a combining character sequence). For more information, see
TextElementEnumerator and The Unicode Standard .
VB
Example 2
It is more difficult to split a string into its Unicode text characters, but this is necessary if
you need information about the visual representation of a string. This example uses the
SubstringByTextElements method to get information about the Unicode text characters
that make up a string.
VB
See also
Chars[]
System.Globalization.StringInfo
How to: Access Characters in Strings
Converting Between Strings and Other Data Types in Visual Basic
Strings
How to: Access Characters in Strings in
Visual Basic
Article • 09/15/2021
This example demonstrates how to use the Chars[] property to access the character at
the specified location in a string.
Example
Sometimes it is useful to have data about the characters in your string and the positions
of those characters within your string. You can think of a string as an array of characters
( Char instances); you can retrieve a particular character by referencing the index of that
character through the Chars[] property.
VB
Robust Programming
The Chars[] property returns the character at the specified position. However, some
Unicode characters can be represented by more than one character. For more
information on how to work with Unicode characters, see How to: Convert a String to an
Array of Characters.
See also
Chars[]
How to: Convert a String to an Array of Characters
Converting Between Strings and Other Data Types in Visual Basic
Strings
Validating Strings in Visual Basic
Article • 09/15/2021
In This Section
How to: Validate File Names and Paths in Visual Basic
How to determine whether a string represents a file name or path.
See also
Strings
MaskedTextBox Control
How to: Validate File Names and Paths
in Visual Basic
Article • 09/15/2021
This example returns a Boolean value that indicates whether a string represents a file
name or path. The validation checks if the name contains characters that are not allowed
by the file system.
Example
VB
This example does not check if the name has incorrectly placed colons, or directories
with no name, or if the length of the name exceeds the system-defined maximum
length. It also does not check if the application has permission to access the file-system
resource with the specified name.
See also
GetInvalidPathChars
Validating Strings in Visual Basic
How to: Validate Strings That Represent
Dates or Times (Visual Basic)
Article • 09/15/2021
The following code example sets a Boolean value that indicates whether a string
represents a valid date or time.
Example
VB
Robust Programming
Use this method to validate the string before trying to convert the String to a DateTime
variable. By checking the date or time first, you can avoid generating an exception at run
time.
See also
IsDate
InputBox
Validating Strings in Visual Basic
Using Regular Expressions with the
MaskedTextBox Control in Visual Basic
Article • 09/15/2021
This example demonstrates how to convert simple regular expressions to work with the
MaskedTextBox control.
platform.
The Mask property of the MaskedTextBox control specifies what input mask to use. The
mask must be a string composed of one or more of the masking elements from the
following table.
All other Literals. All non-mask elements will appear as All other characters.
characters. themselves within MaskedTextBox.
The decimal (.), thousandths (,), time (:), date (/), and currency ($) symbols default to
displaying those symbols as defined by the application's culture. You can force them to
display symbols for another culture by using the FormatProvider property.
The following table compares four regular expressions and the equivalent mask for
each.
\d{2}/\d{2}/\d{4} 00/00/0000 The / character in the mask is a logical date separator, and it
will appear to the user as the date separator appropriate to
the application's current culture.
\d{2}-[A-Z][a-z] 00->L<LL- A date (day, month abbreviation, and year) in United States
{2}-\d{4} 0000 format in which the three-letter month abbreviation is
displayed with an initial uppercase letter followed by two
lowercase letters.
(\(\d{3}\)-)? (999)-000- United States phone number, area code optional. If the user
\d{3}-d{4} 0000 does not wish to enter the optional characters, they can
either enter spaces or place the mouse pointer directly at the
position in the mask represented by the first 0.
Regular Mask Notes
Expression
See also
Mask
MaskedTextBox
Validating Strings in Visual Basic
MaskedTextBox Control
Walkthrough: Validating That Passwords
Are Complex (Visual Basic)
Article • 09/15/2021
This method checks for some strong-password characteristics and updates a string
parameter with information about which checks the password fails.
Passwords can be used in a secure system to authorize a user. However, the passwords
must be difficult for unauthorized users to guess. Attackers can use a dictionary attack
program, which iterates through all of the words in a dictionary (or multiple dictionaries
in different languages) and tests whether any of the words work as a user's password.
Weak passwords such as "Yankees" or "Mustang" can be guessed quickly. Stronger
passwords, such as "?You'L1N3vaFiNdMeyeP@sSWerd!", are much less likely to be
guessed. A password-protected system should ensure that users choose strong
passwords.
Example
Code
VB
' Replace [A-Z] with \p{Lu}, to allow for Unicode uppercase letters.
Dim upper As New System.Text.RegularExpressions.Regex("[A-Z]")
Dim lower As New System.Text.RegularExpressions.Regex("[a-z]")
Dim number As New System.Text.RegularExpressions.Regex("[0-9]")
' Special is "none of the above".
Dim special As New System.Text.RegularExpressions.Regex("[^a-zA-Z0-9]")
Sub TestValidatePassword()
Dim password As String = "Password"
' Demonstrate that "Password" is not complex.
MsgBox(password & " is complex: " & ValidatePassword(password))
password = "Z9f%a>2kQ"
' Demonstrate that "Z9f%a>2kQ" is not complex.
MsgBox(password & " is complex: " & ValidatePassword(password))
End Sub
Security
If you're moving the password across a network, you need to use a secure method for
transferring data. For more information, see ASP.NET Web Application Security.
You can improve the accuracy of the ValidatePassword function by adding additional
complexity checks:
Compare the password and its substrings against the user's name, user identifier,
and an application-defined dictionary. In addition, treat visually similar characters
as equivalent when performing the comparisons. For example, treat the letters "l"
and "e" as equivalent to the numerals "1" and "3".
If there is only one uppercase character, make sure it is not the password's first
character.
Make sure that the last two characters of the password are letter characters.
Do not allow passwords in which all the symbols are entered from the keyboard's
top row.
See also
Regex
ASP.NET Web Application Security
Walkthrough: Encrypting and
Decrypting Strings in Visual Basic
Article • 09/15/2021
This walkthrough shows you how to use the DESCryptoServiceProvider class to encrypt
and decrypt strings using the cryptographic service provider (CSP) version of the Triple
Data Encryption Standard (TripleDES) algorithm. The first step is to create a simple
wrapper class that encapsulates the 3DES algorithm and stores the encrypted data as a
base-64 encoded string. Then, that wrapper is used to securely store private user data in
a publicly accessible text file.
You can use encryption to protect user secrets (for example, passwords) and to make
credentials unreadable by unauthorized users. This can protect an authorized user's
identity from being stolen, which protects the user's assets and provides non-
repudiation. Encryption can also protect a user's data from being accessed by
unauthorized users.
) Important
The Rijndael (now referred to as Advanced Encryption Standard [AES]) and Triple
Data Encryption Standard (3DES) algorithms provide greater security than DES
because they are more computationally intensive. For more information, see DES
and Rijndael.
VB
2. Add an import of the cryptography namespace to the start of the file that contains
the Simple3Des class.
VB
Imports System.Security.Cryptography
3. In the Simple3Des class, add a private field to store the 3DES cryptographic service
provider.
VB
4. Add a private method that creates a byte array of a specified length from the hash
of the specified key.
VB
VB
VB
Public Function EncryptData(
ByVal plaintext As String) As String
' Use the crypto stream to write the byte array to the stream.
encStream.Write(plaintextBytes, 0, plaintextBytes.Length)
encStream.FlushFinalBlock()
VB
' Use the crypto stream to write the byte array to the stream.
decStream.Write(encryptedBytes, 0, encryptedBytes.Length)
decStream.FlushFinalBlock()
The wrapper class can now be used to protect user assets. In this example, it is
used to securely store private user data in a publicly accessible text file.
To test the encryption wrapper
1. In a separate class, add a method that uses the wrapper's EncryptData method to
encrypt a string and write it to the user's My Documents folder.
VB
Sub TestEncoding()
Dim plainText As String = InputBox("Enter the plain text:")
Dim password As String = InputBox("Enter the password:")
2. Add a method that reads the encrypted string from the user's My Documents
folder and decrypts the string with the wrapper's DecryptData method.
VB
Sub TestDecoding()
Dim cipherText As String = My.Computer.FileSystem.ReadAllText(
My.Computer.FileSystem.SpecialDirectories.MyDocuments &
"\cipherText.txt")
Dim password As String = InputBox("Enter the password:")
Dim wrapper As New Simple3Des(password)
3. Add user interface code to call the TestEncoding and TestDecoding methods.
When you test the application, notice that it will not decrypt the data if you
provide the wrong password.
See also
System.Security.Cryptography
DESCryptoServiceProvider
DES
TripleDES
Rijndael
Cryptographic Services