Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

Strings in VB-NET

Working with strings in VbNet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Strings in VB-NET

Working with strings in VbNet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Tell us about your PDF experience.

Strings in Visual Basic


Article • 09/15/2021

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.

How to: Create Strings Using a StringBuilder in Visual Basic


Demonstrates how to efficiently create a long string from many smaller strings.

How to: Search Within a String


Demonstrates how to determine the index of the first occurrence of a substring.

Converting Between Strings and Other Data Types in Visual Basic


Lists topics that describe how to convert strings into other data types.

Validating Strings in Visual Basic


Lists topics that discuss how to validate strings.

Walkthrough: Encrypting and Decrypting Strings in Visual Basic


Demonstrates how to encrypt and decrypt strings by using the cryptographic service
provider version of the Triple Data Encryption Standard algorithm.

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.

Types of String Manipulation Methods in Visual Basic


Introduces several different ways to analyze and manipulate strings.

How Culture Affects Strings in Visual Basic


Discusses how Visual Basic uses culture information to perform string conversions and
comparisons.

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

Dim MyString As String


MyString = "This is an example of the String data type"

A String variable can also accept any expression that evaluates to a string. Examples
are shown below:

VB

Dim OneString As String


Dim TwoString As String
OneString = "one, two, three, four, five"

' Evaluates to "two".


TwoString = OneString.Substring(5, 3)
OneString = "1"

' Evaluates to "11".


TwoString = OneString & "1"

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

Dim myString As String

' This line would cause an error.


' myString = "He said, "Look at this example!""
This code causes an error because the compiler terminates the string after the second
quotation mark, and the remainder of the string is interpreted as code. To solve this
problem, Visual Basic interprets two quotation marks in a string literal as one quotation
mark in the string. The following example demonstrates the correct way to include a
quotation mark in a string:

VB

' The value of myString is: He said, "Look at this example!"


myString = "He said, ""Look at this example!"""

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.

String literals can contain multiple lines:

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

Dim myString As String = "ABCDE"


Dim myChar As Char
' The value of myChar is "D".
myChar = myString.Chars(3)

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

Dim myString As String = "abcdefghijklmnop"


Dim myArray As Char() = myString.ToCharArray

The variable myArray now contains an array of Char values, each representing a
character from myString .

The Immutability of Strings


A string is immutable, which means its value cannot be changed once it has been
created. However, this does not prevent you from assigning more than one value to a
string variable. Consider the following example:

VB

Dim myString As String = "This string is immutable"


myString = "Or is it?"

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.

Visual Basic Language and the .NET Framework


Visual Basic methods are used as inherent functions of the language. They may be used
without qualification in your code. The following example shows typical use of a Visual
Basic string-manipulation command:

VB

Dim aString As String = "SomeString"


Dim bString As String
' Assign "meS" to bString.
bString = Mid(aString, 3, 3)

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 and Instance Methods


You can also manipulate strings with the methods of the String class. There are two
types of methods in String : shared methods and instance methods.

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

Dim aString As String = String.Copy("A literal string")


In the preceding example, the String.Copy method is a static method, which acts upon
an expression it is given and assigns the resulting value to bString .

Instance Methods

Instance methods, by contrast, stem from a particular instance of String and must be
qualified with the instance name. For example:

VB

Dim aString As String = "A String"


Dim bString As String

' Assign "String" to bString.


bString = aString.Substring(2, 6)

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.

Visual Basic Runtime and the .NET Framework


Consider the following example:

VB

Dim MyString As String = "This is my string"


Dim stringLength As Integer

' Explicitly set the string to Nothing.


MyString = Nothing

' stringLength = 0
stringLength = Len(MyString)

' This line, however, causes an exception to be thrown.


stringLength = MyString.Length

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.

When to Use Culture-Specific Strings


Typically, you should use culture-specific strings for all data presented to and read from
users, and use culture-invariant strings for your application's internal data.

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 key to successfully using string-conversion functions in applications that run on


computers with different culture settings is to understand which functions use a specific
culture setting, and which use the current culture setting. Notice that the application's
culture settings are, by default, inherited from the culture settings of the operating
system. For more information, see Asc, AscW, Chr, ChrW, Format, Hex, Oct, and Type
Conversion Functions.

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.

Conversions that use a specific culture. Each number object has a


ToString(IFormatProvider) method that converts a number to a string, and a

Parse(String, IFormatProvider) method that converts a string to a number. For

example, the Double type provides the ToString(IFormatProvider) and Parse(String,


IFormatProvider) methods.

For more information, see Str and Val.

Using a Specific Culture


Imagine that you are developing an application that sends a date (formatted as a string)
to a Web service. In this case, your application must use a specific culture for the string
conversion. To illustrate why, consider the result of using the date's ToString() method: If
your application uses that method to format the date July 4, 2005, it returns "7/4/2005
12:00:00 AM" when run with the United States English (en-US) culture, but it returns
"04.07.2005 00:00:00" when run with the German (de-DE) culture.

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

Dim d As Date = #7/4/2005#


MsgBox(d.ToString(System.Globalization.CultureInfo.InvariantCulture))
7 Note

Date literals are always interpreted according to the English culture.

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.

Determining if two application-internal strings exactly match (typically for


security purposes). Use operations that disregard the current culture.

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

' Defines variables.


Dim testStr1 As String = "ABCD"
Dim testStr2 As String = "abcd"
Dim testComp As Integer
' The two strings sort equally. Returns 0.
testComp = StrComp(testStr1, testStr2, CompareMethod.Text)
' testStr1 sorts before testStr2. Returns -1.
testComp = StrComp(testStr1, testStr2, CompareMethod.Binary)
' testStr2 sorts after testStr1. Returns 1.
testComp = StrComp(testStr2, testStr1, CompareMethod.Binary)

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

Dim myString As String = "Alphabetical"


Dim secondString As String = "Order"
Dim result As Integer
result = String.Compare(myString, secondString)

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.

Value for comparisonType Type of comparison When to use


argument

Ordinal Comparison based on strings' Use this value when


component bytes. comparing: case-sensitive
identifiers, security-related
settings, or other non-
linguistic identifiers where the
bytes must match exactly.

OrdinalIgnoreCase Comparison based on strings' Use this value when


component bytes. comparing: case-insensitive
identifiers, security-related
OrdinalIgnoreCase uses the settings, and data stored in
invariant culture information to Windows.
determine when two characters
differ only in capitalization.

CurrentCulture or Comparison based on the Use these values when


CurrentCultureIgnoreCase strings' interpretation in the comparing: data that is
current culture. displayed to the user, most
user input, and other data that
requires linguistic
interpretation.

InvariantCulture or Comparison based on the Use these values only when


InvariantCultureIgnoreCase strings' interpretation in the comparing persisting data or
invariant culture. displaying linguistically-
relevant data that requires a
This is different than the Ordinal fixed sort order.
and OrdinalIgnoreCase , because
the invariant culture treats
characters outside its accepted
range as equivalent invariant
characters.

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.

The arguments of an interpolated string are easier to understand than a composite


format string. For example, the interpolated string

VB

Console.WriteLine($"Name = {name}, hours = {hours:hh}")

contains two interpolated expressions, '{name}' and '{hours:hh}'. The equivalent


composite format string is:

VB

Console.WriteLine("Name = {0}, hours = {1:hh}", name, hours)

The structure of an interpolated string is:

VB

$"<text> {<interpolated-expression> [,<field-width>] [:<format-string>] }


<text> ..."

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.

If the interpolated string contains other characters with special meaning in an


interpolated string, such as the quotation mark ("), colon (:), or comma (,), they should
be escaped if they occur in literal text, or they should be included in an expression
delimited by parentheses if they are language elements included in an interpolated
expression. The following example escapes quotation marks to include them in the
result string:

VB

Public Module Example


Public Sub Main()
Dim name = "Horace"
Dim age = 34
Dim s1 = $"He asked, ""Is your name {name}?"", but didn't wait for a
reply."
Console.WriteLine(s1)

Dim s2 = $"{name} is {age:D3} year{If(age = 1, "", "s")} old."


Console.WriteLine(s2)
End Sub
End Module
' The example displays the following output:
' He asked, "Is your name Horace?", but didn't wait for a reply.
' Horace is 034 years old.

Implicit Conversions
There are three implicit type conversions from an interpolated string:

1. Conversion of an interpolated string to a String. The following example returns a


string whose interpolated string expressions have been replaced with their string
representations. For example:

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.

2. Conversion of an interpolated string to an IFormattable variable that allows you


create multiple result strings with culture-specific content from a single
IFormattable instance. This is useful for including such things as the correct
numeric and date formats for individual cultures. All occurrences of double curly
braces ("{{" and "}}") remain as double curly braces until you format the string by
explicitly or implicitly calling the ToString() method. All contained interpolation
expressions are converted to {0}, {1}, and so on.

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

Public Module Example


Public Sub Main()
Dim price = 1000
Dim s2 As IFormattable = $"The cost of this item is {price:C}."
ShowInfo(s2)
CultureInfo.CurrentCulture = New CultureInfo("en-US")
Console.WriteLine(s2)
CultureInfo.CurrentCulture = New CultureInfo("fr-FR")
Console.WriteLine(s2)
End Sub

Private Sub ShowInfo(obj As Object)


Console.WriteLine($"Displaying member information:{vbCrLf}")
Dim t = obj.GetType()
Dim flags = BindingFlags.Public Or BindingFlags.Instance Or
BindingFlags.Static Or BindingFlags.NonPublic
For Each m In t.GetMembers(flags)
Console.Write($" {m.Name} {m.MemberType}")
If m.MemberType = MemberTypes.Property Then
Dim p = t.GetProperty(m.Name, flags)
Console.Write($" Value: {p.GetValue(obj)}")
End If
If m.MemberType = MemberTypes.Field Then
Dim f = t.GetField(m.Name, flags)
Console.Write($" Value: {f.GetValue(obj)}")
End If
Console.WriteLine()
Next
Console.WriteLine($"-------{vbCrLf}")
End Sub
End Module
' The example displays the following output:
Displaying member information:

' get_Format Method


' GetArguments Method
' get_ArgumentCount Method
' GetArgument Method
' ToString Method
' System.IFormattable.ToString Method
' ToString Method
' Equals Method
' GetHashCode Method
' GetType Method
' Finalize Method
' MemberwiseClone Method
' .ctor Constructor
' Format Property Value: The cost of this item is {0:C}.
' ArgumentCount Property Value: 1
' _format Field Value: The cost of this item is {0:C}.
' _arguments Field Value: System.Object[]
' -------
'
' The cost of this item is $1,000.00.
' The cost of this item is 1 000,00 €.
' </Snippet1>

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.

3. Conversion of an interpolated string to a FormattableString variable that


represents a composite format string. Inspecting the composite format string and
how it renders as a result string might, for example, help you protect against an
injection attack if you were building a query. A FormattableString also includes:
A ToString() overload that produces a result string for the CurrentCulture.

An Invariant method that produces a string for the InvariantCulture.

A ToString(IFormatProvider) method that produces a result string for a


specified culture.

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

Public Module Example


Public Sub Main()
Dim name = "Bartholomew"
Dim s3 As FormattableString = $"Hello, {name}!"
Console.WriteLine($"String: '{s3.Format}'")
Console.WriteLine($"Arguments: {s3.ArgumentCount}")
Console.WriteLine($"Result string: {s3}")
End Sub
End Module
' The example displays the following output:
' String: 'Hello, {0}!'
' Arguments: 1
' Result string: Hello, Bartholomew!

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

Private Function StringBuilderTest() As String


Dim builder As New System.Text.StringBuilder
For i As Integer = 1 To 1000
builder.Append("Step " & i & vbCrLf)
Next
Return builder.ToString
End Function

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

Dim SearchWithinThis As String = "ABCDEFGHIJKLMNOP"


Dim SearchForThis As String = "DEF"
Dim FirstCharacter As Integer = SearchWithinThis.IndexOf(SearchForThis)

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.

If IndexOf does not find the substring, it returns -1.

The IndexOf method is case-sensitive and uses the current culture.

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.

How to: Convert Strings into an Array of Bytes in Visual Basic


How to convert a string into an array of bytes.

How to: Create a String from An Array of Char Values


How to create the string "abcd" from individual characters.

How to: Convert Hexadecimal Strings to Numbers


How to convert a hexadecimal string into an integer.

How to: Convert a String to an Array of Characters in Visual Basic


How to convert a string into an array of characters.

How to: Access Characters in Strings in Visual Basic


How to access a character in a string by its index.
How to: Convert an Array of Bytes into a
String in Visual Basic
Article • 09/15/2021

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

Private Function UnicodeBytesToString(


ByVal bytes() As Byte) As String

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.ASCII: Gets an encoding for the ASCII (7-bit) character set.

Encoding.BigEndianUnicode: Gets an encoding for the UTF-16 format using the


big-endian byte order.

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.

Encoding.UTF7: Gets an encoding for the UTF-7 format.

Encoding.UTF8: Gets an encoding for the UTF-8 format.

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

This topic shows how to convert a string into an array of bytes.

Example
This example uses the GetBytes method of the Encoding.Unicode encoding class to
convert a string into an array of bytes.

VB

Private Function UnicodeStringToBytes(


ByVal str As String) As Byte()

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.ASCII: Gets an encoding for the ASCII (7-bit) character set.

Encoding.BigEndianUnicode: Gets an encoding for the UTF-16 format using the


big-endian byte order.

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.

Encoding.UTF7: Gets an encoding for the UTF-7 format.

Encoding.UTF8: Gets an encoding for the UTF-8 format.

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

This example creates the string "abcd" from individual characters.

Example
VB

Private Sub MakeStringFromCharacters()


Dim characters() As Char = {"a"c, "b"c, "c"c, "d"c}
Dim alphabet As New String(characters)
End Sub

Compile the code


This method has no special requirements.

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

This example converts a hexadecimal string to an integer using the Convert.ToInt32


method.

To convert a hexadecimal string to a number


Use the ToInt32(String, Int32) method to convert the number expressed in base-16
to an integer.

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

' Assign the value 49153 to i.


Dim i As Integer = Convert.ToInt32("c001", 16)

Note that the hexadecimal string has the following restrictions:


It cannot include the &h prefix.
It cannot include the _ digit separator.

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

Dim testString1 As String = "ABC"


' Create an array containing "A", "B", and "C".
Dim charArray() As Char = testString1.ToCharArray

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

' This string is made up of a surrogate pair (high surrogate


' U+D800 and low surrogate U+DC00) and a combining character
' sequence (the letter "a" with the combining grave accent).
Dim testString2 As String = ChrW(&HD800) & ChrW(&HDC00) & "a" & ChrW(&H300)

' Create and initialize a StringInfo object for the string.


Dim si As New System.Globalization.StringInfo(testString2)

' Create and populate the array.


Dim unicodeTestArray(si.LengthInTextElements - 1) As String
For i As Integer = 0 To si.LengthInTextElements - 1
unicodeTestArray(i) = si.SubstringByTextElements(i, 1)
Next

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

Dim myString As String = "ABCDE"


Dim myChar As Char

' Assign "D" to myChar.


myChar = myString.Chars(3)

The index parameter of the Chars[] property is zero-based.

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.

The Chars[] property throws an IndexOutOfRangeException exception if the index


parameter is greater than or equal to the length of the string, or if it is less than zero

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

This section discusses how to validate strings in Visual Basic.

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.

How to: Validate Strings That Represent Dates or Times


How to determine whether a string represents a valid date.

Using Regular Expressions with the MaskedTextBox Control in Visual Basic


Demonstrates how to convert simple regular expressions to work with the
MaskedTextBox control.

Walkthrough: Validating That Passwords Are Complex


How to determine whether a string has the characteristics of a strong password.

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

Function IsValidFileNameOrPath(ByVal name As String) As Boolean


' Determines if the name is Nothing.
If name Is Nothing Then
Return False
End If

' Determines if there are bad characters in the name.


For Each badChar As Char In System.IO.Path.GetInvalidPathChars
If InStr(name, badChar) > 0 Then
Return False
End If
Next

' The name passes basic validation.


Return True
End Function

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

Dim isValidDate As Boolean = IsDate("01/01/03")


Dim isValidTime As Boolean = IsDate("9:30 PM")

Compile the code


Replace ("01/01/03") and "9:30 PM" with the date and time you want to validate. You
can replace the string with another hard-coded string, with a String variable, or with a
method that returns a string, such as InputBox .

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.

Description of the Masking Language


The standard MaskedTextBox masking language is based on the one used by the Masked
Edit control in Visual Basic 6.0 and should be familiar to users migrating from that

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.

Masking Description Regular expression element


element

0 Any single digit between 0 and 9. Entry required. \d

9 Digit or space. Entry optional. [ \d]?

# Digit or space. Entry optional. If this position is left [ \d+-]?


blank in the mask, it will be rendered as a space.
Plus (+) and minus (-) signs are allowed.

L ASCII letter. Entry required. [a-zA-Z]

? ASCII letter. Entry optional. [a-zA-Z]?

& Character. Entry required. [\p{Ll}\p{Lu}\p{Lt}\p{Lm}\p{Lo}]

C Character. Entry optional. [\p{Ll}\p{Lu}\p{Lt}\p{Lm}\p{Lo}]?

A Alphanumeric. Entry optional. \W

. Culture-appropriate decimal placeholder. Not available.

, Culture-appropriate thousands placeholder. Not available.

: Culture-appropriate time separator. Not available.

/ Culture-appropriate date separator. Not available.


Masking Description Regular expression element
element

$ Culture-appropriate currency symbol. Not available.

< Converts all characters that follow to lowercase. Not available.

> Converts all characters that follow to uppercase. Not available.

| Undoes a previous shift up or shift down. Not available.

\ Escapes a mask character, turning it into a literal. \


"\\" is the escape sequence for a backslash.

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.

Regular Expressions and Masks


Although you can use regular expressions and masks to validate user input, they are not
completely equivalent. Regular expressions can express more complex patterns than
masks, but masks can express the same information more succinctly and in a culturally
relevant format.

The following table compares four regular expressions and the equivalent mask for
each.

Regular Mask Notes


Expression

\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

$\d{6}.00 $999,999.00 A currency value in the range of 0 to 999999. The currency,


thousandth, and decimal characters will be replaced at run
time with their culture-specific equivalents.

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.

A strong password is complex (containing a mixture of uppercase, lowercase, numeric,


and special characters) and is not a word. This example demonstrates how to verify
complexity.

Example

Code
VB

''' <summary>Determines if a password is sufficiently complex.</summary>


''' <param name="pwd">Password to validate</param>
''' <param name="minLength">Minimum number of password characters.</param>
''' <param name="numUpper">Minimum number of uppercase characters.</param>
''' <param name="numLower">Minimum number of lowercase characters.</param>
''' <param name="numNumbers">Minimum number of numeric characters.</param>
''' <param name="numSpecial">Minimum number of special characters.</param>
''' <returns>True if the password is sufficiently complex.</returns>
Function ValidatePassword(ByVal pwd As String,
Optional ByVal minLength As Integer = 8,
Optional ByVal numUpper As Integer = 2,
Optional ByVal numLower As Integer = 2,
Optional ByVal numNumbers As Integer = 2,
Optional ByVal numSpecial As Integer = 2) As Boolean

' 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]")

' Check the length.


If Len(pwd) < minLength Then Return False
' Check for minimum number of occurrences.
If upper.Matches(pwd).Count < numUpper Then Return False
If lower.Matches(pwd).Count < numLower Then Return False
If number.Matches(pwd).Count < numNumbers Then Return False
If special.Matches(pwd).Count < numSpecial Then Return False

' Passed all checks.


Return True
End Function

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

Compile the code


Call this method by passing the string that contains that password.

This example requires:

Access to the members of the System.Text.RegularExpressions namespace. Add an


Imports statement if you are not fully qualifying member names in your code. For
more information, see Imports Statement (.NET Namespace and Type).

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.

For more information, see Cryptographic Services.

) 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.

To create the encryption wrapper


1. Create the Simple3Des class to encapsulate the encryption and decryption
methods.

VB

Public NotInheritable Class Simple3Des


End Class

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

Private TripleDes As New TripleDESCryptoServiceProvider

4. Add a private method that creates a byte array of a specified length from the hash
of the specified key.

VB

Private Function TruncateHash(


ByVal key As String,
ByVal length As Integer) As Byte()

Dim sha1 As New SHA1CryptoServiceProvider

' Hash the key.


Dim keyBytes() As Byte =
System.Text.Encoding.Unicode.GetBytes(key)
Dim hash() As Byte = sha1.ComputeHash(keyBytes)

' Truncate or pad the hash.


ReDim Preserve hash(length - 1)
Return hash
End Function

5. Add a constructor to initialize the 3DES cryptographic service provider.

The key parameter controls the EncryptData and DecryptData methods.

VB

Sub New(ByVal key As String)


' Initialize the crypto provider.
TripleDes.Key = TruncateHash(key, TripleDes.KeySize \ 8)
TripleDes.IV = TruncateHash("", TripleDes.BlockSize \ 8)
End Sub

6. Add a public method that encrypts a string.

VB
Public Function EncryptData(
ByVal plaintext As String) As String

' Convert the plaintext string to a byte array.


Dim plaintextBytes() As Byte =
System.Text.Encoding.Unicode.GetBytes(plaintext)

' Create the stream.


Dim ms As New System.IO.MemoryStream
' Create the encoder to write to the stream.
Dim encStream As New CryptoStream(ms,
TripleDes.CreateEncryptor(),
System.Security.Cryptography.CryptoStreamMode.Write)

' Use the crypto stream to write the byte array to the stream.
encStream.Write(plaintextBytes, 0, plaintextBytes.Length)
encStream.FlushFinalBlock()

' Convert the encrypted stream to a printable string.


Return Convert.ToBase64String(ms.ToArray)
End Function

7. Add a public method that decrypts a string.

VB

Public Function DecryptData(


ByVal encryptedtext As String) As String

' Convert the encrypted text string to a byte array.


Dim encryptedBytes() As Byte =
Convert.FromBase64String(encryptedtext)

' Create the stream.


Dim ms As New System.IO.MemoryStream
' Create the decoder to write to the stream.
Dim decStream As New CryptoStream(ms,
TripleDes.CreateDecryptor(),
System.Security.Cryptography.CryptoStreamMode.Write)

' Use the crypto stream to write the byte array to the stream.
decStream.Write(encryptedBytes, 0, encryptedBytes.Length)
decStream.FlushFinalBlock()

' Convert the plaintext stream to a string.


Return System.Text.Encoding.Unicode.GetString(ms.ToArray)
End Function

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:")

Dim wrapper As New Simple3Des(password)


Dim cipherText As String = wrapper.EncryptData(plainText)

MsgBox("The cipher text is: " & cipherText)


My.Computer.FileSystem.WriteAllText(
My.Computer.FileSystem.SpecialDirectories.MyDocuments &
"\cipherText.txt", cipherText, False)
End Sub

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)

' DecryptData throws if the wrong password is used.


Try
Dim plainText As String = wrapper.DecryptData(cipherText)
MsgBox("The plain text is: " & plainText)
Catch ex As System.Security.Cryptography.CryptographicException
MsgBox("The data could not be decrypted with the password.")
End Try
End Sub

3. Add user interface code to call the TestEncoding and TestDecoding methods.

4. Run the application.

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

You might also like