|
|
|
String is a powerful datatype which you use everyday. VB.net gives you great functionality with String class. In this article we will see some common functions of string class and will also learn about StringBuilder class for very fast string operations.
Facts about String class
1. The .NET Framework System.String class (or its alias, string) represents an immutable string of characters—immutable because its value can’t be modified once it’s been created. Methods that appear to modify a string actually return a new string containing the modification. For faster string operations always consider System.Text.StringBuilder class
2. In VB.net fixed length string is now allowed. (e.g. Dim str As String*25 is valid in VB6 but invalid in VB.net)
3. All string operations are case-sensitive when you use methods from String class.
4. You can also use VB6 style string functions which are defined in "Strings" module. (e.g. Strings.Replace ). Some methods takes Compare type argument which can be Binary (Case-sensitive) or Text (Case-insensitive).
5. In VB.net each string character takes 2 bytes because VB.net strings are Unicode (2 bytes per character)
Members of string class |
Public Properties
Chars |
Gets the character at a specified
character position in this instance.
|
Length |
Gets the number of characters in this
instance. |
Public Methods
Clone |
Returns a reference to this instance of
String
|
Compare |
Overloaded. Compares two specified
String
|
CompareOrdinal |
Overloaded. Compares two String
objects by evaluating the numeric values of the
corresponding
Char
|
CompareTo |
Overloaded. Compares this instance with
a specified object. |
Concat |
Overloaded. Concatenates one or more
instances of String, or the String
representations of the values of one or more instances
of
Object
|
Copy |
Creates a new instance of String
with the same value as a specified String
|
CopyTo |
Copies a specified number of characters
from a specified position in this instance to a
specified position in an array of Unicode characters. |
EndsWith |
Determines whether the end of this
instance matches the specified String
|
Equals |
Overloaded. Overridden. Determines
whether two String
|
Format |
Overloaded. Replaces each format item in
a specified String
|
GetEnumerator |
Retrieves an object that can iterate
through the individual characters in this instance. |
GetHashCode |
Overridden. Returns the hash code for
this instance. |
GetType
(inherited from Object) |
Gets the
Type
|
GetTypeCode |
Returns the
TypeCode for class String
|
IndexOf |
Overloaded. Reports the index of the
first occurrence of a a String, or one or more
characters, within this instance. |
IndexOfAny |
Overloaded. Reports the index of the
first occurrence in this instance of any character in a
specified array of Unicode characters. |
Insert |
Inserts a specified instance of of
String at a specified index position in this
instance. |
Intern |
Retrieves the system's reference to the
specified ed String. |
IsInterned |
Retrieves a reference to a specified ed
String. |
Join |
Overloaded. Concatenates a specified
separator or String between each element of a
specified String array, yielding a single
concatenated string. |
LastIndexOf |
Overloaded. Reports the index position
of the last occurrence of a specified Unicode character
or or String within this instance. |
LastIndexOfAny |
Overloaded. Reports the index position
of the last occurrence in this instance of one or more
characters specified in a Unicode array. |
PadLeft |
Overloaded. Right-aligns the characters
in this instance, padding on the left with spaces or a
specified Unicode character for a specified total
length. |
PadRight |
Overloaded. Left-aligns the characters
in this string, padding on the right with spaces or a
specified Unicode character, for a specified total
length. |
Remove |
Deletes a specified number of characters
from this instance beginning at a specified position. |
Replace |
Overloaded. Replaces all occurrences of
a specified Unicode character or or String in this
instance, with another specified Unicode character or
String. |
Split |
Overloaded. Identifies the substrings in
this instance that are delimited by one or more
characters specified in an array, then places the
substrings into a a String array. |
StartsWith |
Determines whether the beginning of this
instance matches the specified ed String. |
Substring |
Overloaded. Retrieves a substring from
this instance. |
ToCharArray |
Overloaded. Copies the characters in
this instance to a Unicode character array. |
ToLower |
Overloaded. Returns a copy of this is
String in lowercase. |
ToString |
Overloaded. Overridden. Converts the
value of this instance to a a String. |
ToUpper |
Overloaded. Returns a copy of this is
String in uppercase. |
Trim |
Overloaded. Removes all occurrences of a
set of specified characters from the beginning and end
of this instance. |
TrimEnd |
Removes all occurrences of a set of
characters specified in an array from the end of this
instance. |
TrimStart |
Removes all occurrences of a set of
characters specified in an array from the beginning of
this instance.ce. |
Finalize
(inherited from Object) |
Overridden. Allows an
Object to attempt to free resources and perform
other cleanup operations before the Object is
reclaimed by garbage collection. |
MemberwiseClone
(inherited from Object) |
Creates a shallow copy of the current
Object |
|
|
Trim, TrimStart, TrimEnd
VB.net version of Trim function is more useful than previous version. VB.net Trim functions of string class not only trims white spaces but you can also remove a specified characters which makes more sense in many cases when you have some unwanted characters at the end of the string. e.g.
- Trim last "\" from file path - Trim last "," from CSV string
Trimming spaces |
"some string"
"some string "
" some string"
|
Trimming specified set of characters |
Click here to copy the following block | Dim strCh As String = "$#%" Dim str As String = "###$$$%%%some string$%##$##"
Console.WriteLine(str.Trim(strCh.ToCharArray)) Console.WriteLine(str.TrimStart(strCh.ToCharArray)) Console.WriteLine(str.TrimEnd(strCh.ToCharArray)) |
"some string"
"some string$%##$##"
"###$$$%%%some string"
|
Joinning strings with a specified seperator (String.Join method)
String.Join method can be used to join one or more strings with a specified seperator.
Example |
Click here to copy the following block | Dim val As String() = {"apple", "orange", "grape", "pear", "mango"} Dim sep As String = " | " Dim result As [String]
Console.WriteLine("sep = '{0}'", sep) Console.WriteLine("val() = {{'{0}' '{1}' '{2}' '{3}' '{4}'}}", val(0), val(1), val(2), val(3), val(4))
result = String.Join(sep, val) Console.WriteLine("String.Join(sep, val) = '{0}'", result)
result = String.Join(sep, val, 1, 2) Console.WriteLine("String.Join(sep, val, 1, 2) = '{0}'", result) |
sep = ' | '
val() = {'apple' 'orange' 'grape' 'pear' 'mango'}
String.Join(sep, val) = 'apple | orange | grape | pear | mango'
String.Join(sep, val, 1, 2) = 'orange | grape' |
Checking start and end of a string (String.StartsWith, String.EndsWith methods)
String.StartsWith method makes a comparison at the beginning of the string, determines whether it matches this current instance, and returns a Boolean representation of their relationship.
String.EndsWith method makes a comparison at the end of the string, determines whether it matches this current instance, and returns a Boolean representation of their relationship.
Both methods perform a word (case-sensitive and culture-sensitive) search using the current culture.
Example |
Click here to copy the following block | Dim sFile As String = "C:\Setup.Bmp"
If sFile.ToLower.EndsWith(".bmp") Then Console.WriteLine("Its BMP file") Else Console.WriteLine("Its not BMP file") End If
If sFile.ToLower.StartsWith("c:\") Then Console.WriteLine("file found on c: ") Else Console.WriteLine("file not found on c:") End If |
Its BMP file
file found on c: |
IndexOf, LastIndexOf, IndexOfAny and LastIndexOfAny
All this functions are very useful when searching for substring or character within string.
IndexOf and IndexOfAny returns position of first occurance of substring or character you want to search. It returns -1 if no match found.
LastIndexOf and LastIndexOfAny returns position of last occurance of substring or character you want to search. It returns -1 if no match found.
find first or last match (IndexOf, LastIndexOf) |
Click here to copy the following block | Dim strSource As String = "AB-CD-EF-GH-IJ" Dim strSearch As String Dim foundAtFirst, foundAtLast As Integer
strSearch = "-" foundAtFirst = strSource.IndexOf(strSearch) foundAtLast = strSource.LastIndexOf(strSearch)
If foundAtFirst > -1 And foundAtLast > -1 Then Console.WriteLine("First match of '{0}' found at pos {1} in string '{2}'", strSearch, foundAtFirst, strSource) Console.WriteLine("Last match of '{0}' found at pos {1} in string '{2}'", strSearch, foundAtLast, strSource) Else Console.WriteLine("'{0}' not found in '{1}'", strSearch, strSource) End If |
First match of '-' found at pos 2 in string 'AB-CD-EF-GH-IJ'
Last match of '-' found at pos 11 in string 'AB-CD-EF-GH-IJ'
|
find all matches (IndexOf) |
Click here to copy the following block | Dim strSource As String = "AB-CD-EF-GH-IJ-" Dim strSearch As String Dim startIdx, sLen, count As Integer Dim foundAt As Integer
strSearch = "-"
count = 0 foundAt = 0 startIdx = 0 sLen = strSource.Length
Console.WriteLine("Finding all occurances for '{0}' in string '{1}'", strSearch, strSource)
While startIdx <= sLen AndAlso foundAt > -1 count = sLen - startIdx foundAt = strSource.IndexOf(strSearch, startIdx, count) If foundAt = -1 Then Exit While End If Console.Write("{0} ", foundAt) startIdx = foundAt + 1 End While |
Finding all occurances for '-' in string 'AB-CD-EF-GH-IJ-'
Found at 2
Found at 5
Found at 8
Found at 11
Found at 14 |
Find any character from given set of characters (IndexOfAny, LastIndexOfAny) |
Click here to copy the following block | Dim strSource As String = "AB-CD@EF-GH#IJ" Dim charsToSearch As String Dim foundAtFirstAny, foundAtLastAny As Integer
charsToSearch = "@#$" foundAtFirstAny = strSource.IndexOfAny(charsToSearch.ToCharArray) foundAtLastAny = strSource.LastIndexOfAny(charsToSearch.ToCharArray)
If foundAtFirstAny > -1 And foundAtLastAny > -1 Then Console.WriteLine("First match from characters [{0}] found at pos {1} in string '{2}'", charsToSearch, foundAtFirstAny, strSource) Console.WriteLine("Last match from characters [{0}] found at pos {1} in string '{2}'", charsToSearch, foundAtLastAny, strSource) Else Console.WriteLine("No charcater from [{0}] is found in '{1}'", charsToSearch, strSource) End If |
First match from characters [@#$] found at pos 5 in string 'AB-CD@EF-GH#IJ'
Last match from characters [@#$] found at pos 11 in string 'AB-CD@EF-GH#IJ'
|
Retriving substring at a given position (Substring)
We saw an example of IndexOf method which returns position of a substring within string instance. Now what if you need substring starting at a spicific position. Well for that you can use Substring method which returns a substring for a specified length and starting at a specified position. |
Click here to copy the following block | Dim info As String() = {"Name: Mr. Smith", "Age: 47", "City: Atlanta", "State: GA"} Dim found As Integer = 0 Dim str, s As String
Console.WriteLine("The initial values in the array are:") For Each s In info Console.WriteLine(s) Next s
Console.WriteLine("{0}We want to retrieve only the key information. That is:", Environment.NewLine)
For Each s In info found = s.IndexOf(":") Console.WriteLine(s.Substring((found + 1)).Trim()) Next s |
The initial values in the array are:
Name: Mr. Smith
Age: 47
City: Atlanta
State: GA
We want to retrieve only the key information. That is:
Mr. Smith
47
Atlanta
GA
|
Insert and Remove range of characters from string (String.Remove, String.Insert)
Now .Net made it easy to remove or insert specified range of characters using a single method String.Remove() . |
123456789
123456@@@@@@789
|
Padding string (String.PadLeft, String.PadRight)
When creating some sort of formatted output you generally need fixed width string with left or right alignment. You can use various functions for this. Common methods of string class are PadLeft and PadRight . One advantage of using these methods is you can define custom pad character other than space. |
Click here to copy the following block | Dim s As String = "12345" Dim stemp As String
Console.WriteLine(s.PadLeft(10)) Console.WriteLine(s.PadLeft(10, "@"))
Console.WriteLine(s.PadRight(10)) Console.WriteLine(s.PadRight(10, "@"))
Console.WriteLine(String.Format("{0,10}", s)) Console.WriteLine(String.Format("{0,-10}", s)) |
'//Pad left using String.PadLeft
12345
@@@@@12345
'//Pad right using String.PadRight
12345
12345@@@@@
'//Padding using String.Format() - Only space can be used as pad character
12345
12345
|
Formatting string (String.Format)
String.Format is a very powerful function for string formatting. Using this function you can not only only format string but you can apply formatting rules for numbers, date and currency. String.Format and Console.Write both use same string format rules.
The .NET Framework provides a customizable, general-purpose formatting mechanism to convert a value into a string suitable for display. For example, a numeric value can be formatted in hexadecimal, scientific notation, or a series of digits separated into groups with a user-specified punctuation mark. Dates and times can be formatted as appropriate for a particular country, region, or culture. An enumerated constant can be formatted as its numeric value or its name.
String.Format method has 5 overloaded definations which take different arguments. |
Public Shared Function Format(ByVal format As String, ByVal arg0 As Object) As String
Public Shared Function Format(ByVal format As String, ByVal arg0 As Object, ByVal arg1 As Object) As String
Public Shared Function Format(ByVal format As String, ByVal arg0 As Object, ByVal arg1 As Object, ByVal arg2 As Object) As String
Public Shared Function Format(ByVal format As String, ByVal ParamArray args() As Object) As String
Public Shared Function Format(ByVal provider As System.IFormatProvider, ByVal format As String, ByVal ParamArray args() As Object) As String
|
Let's look at few examples of String.Format() method. |
Click here to copy the following block | Dim MyNumber As Single = 100000.99 Dim MyString As String = "Joe"
Console.WriteLine(String.Format("{0}", MyString)) Console.WriteLine(String.Format("{0}", MyNumber))
Console.WriteLine(String.Format("{0:C}", MyNumber)) Console.WriteLine(String.Format("{0:C1}", MyNumber)) Console.WriteLine(String.Format("{0:C3}", MyNumber))
Console.WriteLine(String.Format("{0,10}", "Joe")) Console.WriteLine(String.Format("{0,-10}", "Joe")) Console.WriteLine(String.Format("{0,10:C}", MyNumber)) Console.WriteLine(String.Format("{0,-10:C}", MyNumber))
Console.WriteLine(String.Format("Name => {0} Bill amount => {1} ", MyString, MyNumber))
Console.WriteLine(String.Format("Name => {0,10} Bill amount => {1:C} ", MyString, MyNumber))
Console.WriteLine(String.Format("Year=>{0} Month=>{1} Day=>{2} Hour=>{3} Minute=>{4} .... FullDate=>{1}/{2}/{0}", _ Now.Year, Now.Month, Now.Day, Now.Hour, Now.Minute)) |
Joe
100000.22
$100,000.22
$100,000.2
$100,000.220
Joe
Joe
$100,000.22
$100,000.22
Name => Joe Bill amount => 100000.22
Name => Joe Bill amount => $100,000.22
Year=>2005 Month=>8 Day=>20 Hour=>22 Minute=>21 .... FullDate=>8/20/2005
|
Alrite now lets understand how formatting works. Format function allows you to define indexed place holder and you can specify formatting for each place holder. Here is the basic syntax for format item
Format Item Syntax
Each format item takes the following form.
{index[,alignment][:formatString]}
The matching braces ("{" and "}") are required. Because opening and closing braces are interpreted as starting and ending a format item, you must specify two opening braces ("{{") in the fixed text to display one opening brace ("{"), and specify two closing braces ("}}") in the fixed text to display one closing brace ("}").
index : The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corresponding element in the list of values. for example if you put {0} in your string that is your first format item and it corrosponds to arg0 in the String.Format method similarly {1} is format item for arg1 and so on.
alignment : The optional alignment component is a signed integer indicating the preferred formatted field width. -Ve width indicates left alignment and +Ve (which is default) indicates right alignement. When you define width then all unused characters are padded with spaces.
formatString : The optional formatString component consists of standard or custom format specifiers. If formatString is not specified, the general ("G") format specifier is used. The colon is required if formatString is specified.
Now lets look at some predefined format specifier which can be used to format numbers, currency and datetime.
Standard Numeric Format Specifier
Standard numeric format strings are used to format common numeric types. A standard format string takes the form Axx where A is a single alphabetic character called the format specifier, and xx is an optional integer called the precision specifier. The format specifier must be one of the built-in format characters. The precision specifier ranges from 0 to 99 and controls the number of significant digits or zeros to the right of a decimal. The format string cannot contain white spaces. |
Format Specifier |
Name |
Example |
Output |
C or c |
Currency |
Console.WriteLine(String.Format("{0:C}", 12345))
Console.WriteLine(String.Format("{0:C}", -12345))
Console.WriteLine(String.Format("{0:C0}", 12345.22))
Console.WriteLine(String.Format("{0:C}", 12345.9555))
Console.WriteLine(String.Format("{0:C3}", 12345.9555))
Console.WriteLine(String.Format("{0:C4}", 12345.9555))
|
$12,345.00
($12,345.00)
$12,345
$12,345.96
$12,345.956
$12,345.9555 |
D or d |
Decimal (Whole Number) |
Console.WriteLine(String.Format("{0:D}", 12345))
Console.WriteLine(String.Format("{0:D}", -12345))
Console.WriteLine(String.Format("{0:D8}", 12345))
Console.WriteLine(String.Format("{0:D}", 2345.22))
|
12345
-12345
00012345
System.FormatException (Value must
be a whole number) |
E or e |
Scientific (exponential) |
Console.WriteLine(String.Format("{0:E}", 12345.6789))
Console.WriteLine(String.Format("{0:E2}", 12345.6789))
Console.WriteLine(String.Format("{0:E5}", 12345.6789))
Console.WriteLine(String.Format("{0:E10}", 12345.6789))
|
1.234568E+004
1.23E+004
1.23457E+004
1.2345678900E+004 |
F or f |
Fixed point |
Console.WriteLine(String.Format("{0:F}", 12345))
Console.WriteLine(String.Format("{0:F}", 12345.6789))
Console.WriteLine(String.Format("{0:F0}", 12345.6789))
Console.WriteLine(String.Format("{0:F2}", 12345.6789))
Console.WriteLine(String.Format("{0:F5}", 12345.6789))
Console.WriteLine(String.Format("{0:F10}", 12345.6789)) |
12345.00
12345.68
12346
12345.68
12345.67890
12345.6789000000
|
G or g |
General |
Console.WriteLine(String.Format("{0:G}", 12345))
Console.WriteLine(String.Format("{0:G}", 12345.6789))
Console.WriteLine(String.Format("{0:G6}", 12345.6789))
Console.WriteLine(String.Format("{0:G7}", 12345.6789)) |
12345
12345.6789
12345.7
12345.68
|
N or n |
Number |
Console.WriteLine(String.Format("{0:N}", 123456789))
Console.WriteLine(String.Format("{0:N}", 12345.6789))
Console.WriteLine(String.Format("{0:N0}", 12345.6789))
Console.WriteLine(String.Format("{0:N4}", 12345.6789))
Console.WriteLine(String.Format("{0:N6}", 12345.6789)) |
123,456,789.00
12,345.68
12,346
12,345.6789
12,345.678900
|
P or p |
Percentage |
Console.WriteLine(String.Format("{0:P}", 0.9589))
Console.WriteLine(String.Format("{0:P3}", 0.9589))
Console.WriteLine(String.Format("{0:P}", 9589))
|
95.89 %
95.890 %
958,900.00 % |
R or r |
Round-trip (No rounding) |
Console.WriteLine(String.Format("{0:R}", 0.9589))
Console.WriteLine(String.Format("{0:R}", 9589)) |
0.9589
System.FormatException |
X or x |
Hexadecimal |
Console.WriteLine(String.Format("{0:X}", 15))
Console.WriteLine(String.Format("{0:X4}", 15))
Console.WriteLine(String.Format("{0:X}", 15.22))
|
F
000F
System.FormatException |
|
Custom Numeric Format Strings
If the standard numeric format specifiers do not provide the type of formatting you require, you can use custom format strings to further enhance string output.
The following table shows the characters you can use to create custom numeric format strings and their definitions. |
Format Character |
Name |
Example |
Output |
0 |
Zero placeholder |
Console.WriteLine(String.Format("{0:0000}", 15))
Console.WriteLine(String.Format("{0:0000.00}", 15))
Console.WriteLine(String.Format("{0:0000.0000}", 15.68))
|
0015
0015.00
0015.6800 |
# |
Digit placeholder |
Console.WriteLine(String.Format("{0:(###) ###-####}",
8003334444))
Console.WriteLine(String.Format("{0:(###) ###-####}", 3334444))
Console.WriteLine(String.Format("{0:##.##}", 22))
Console.WriteLine(String.Format("{0:##.##}", 22.567))
Console.WriteLine(String.Format("{0:Dollar ##.##}", 22))
|
(800) 333-4444
() 333-4444
22
22.57
Dollar 22 |
. |
Decimal point |
Console.WriteLine(String.Format("{0:0000.00}", 15))
Console.WriteLine(String.Format("{0:0000.0000}", 15.68)
|
0015.00
0015.6800 |
, |
Thousand separator |
Console.WriteLine(String.Format("{0:#,#}", 1234567890))
Console.WriteLine(String.Format("{0:#,#}", 1234567890))
Console.WriteLine(String.Format("{0:#,}", 1234567890))
Console.WriteLine(String.Format("{0:#,,}", 1234567890))
Console.WriteLine(String.Format("{0:#,,,}", 1234567890))
Console.WriteLine(String.Format("{0:#,#,,}", 1234567890))
Console.WriteLine(String.Format("{0:#,#,#,}", 1234567890))
Console.WriteLine(String.Format("{0:######,#.##}", 12345.6789))
Console.WriteLine(String.Format("{0:000000,0.00}", 12345.6789))
|
1,234,567,890
1,234,567,890
1234568
1235
1
1,235
1,234,568
12,345.68
0,012,345.68 |
,. |
Number scaling |
Console.WriteLine(String.Format("{0:0,.}", 1234567890))
Console.WriteLine(String.Format("{0:0,,.}", 1234567890))
Console.WriteLine(String.Format("{0:0,,,.}", 1234567890))
|
1234568
1235
1 |
% |
Percent |
Console.WriteLine(String.Format("{0:#0.##%}",
0.5896788))
|
58.97% |
'ABC' or "ABC" |
Literal |
Console.WriteLine(String.Format("{0:'Hellooo=>' 00.00}",
0.5896788))
|
Hellooo 00.59 |
e |
Exponent placeholder |
Console.WriteLine(String.Format("{0:0.###E+0}", 86000))
Console.WriteLine(String.Format("{0:0.###E+000}", 86000))
Console.WriteLine(String.Format("{0:0.###E-000}", 86000))
|
8.6E+4
8.6E+004
8.6E004 |
; |
Group separator |
Console.WriteLine(String.Format("{0:[+VE 0000.00];[-VE
0000.00];[** Zero **]}", 55.22))
Console.WriteLine(String.Format("{0:[+VE 0000.00];[-VE 0000.00];[** Zero
**]}", -55.22))
Console.WriteLine(String.Format("{0:[+VE 0000.00];[-VE 0000.00];[** Zero
**]}", 0))
|
[+VE 0055.22]
[-VE 0055.22]
[** Zero **] |
|
Date and Time Format Strings
DateTime format strings are used to control the formatting produced when a date or time is represented as a string.
DateTime format strings fall into two categories: standard format strings and custom format strings. The custom format strings allow DateTime objects to be formatted for situations where the standard formatting strings are not useful. |
Format Specifier |
Name |
Example |
Output |
d |
Short date pattern |
Console.WriteLine(String.Format("{0:d}", Now)) |
8/22/2005 |
D |
Long date pattern |
Console.WriteLine(String.Format("{0:D}", Now)) |
Monday, August 22, 2005 |
t |
Short time pattern |
Console.WriteLine(String.Format("{0:t}", Now)) |
11:20 PM |
T |
Long time pattern |
Console.WriteLine(String.Format("{0:T}", Now)) |
11:20:55 PM |
f |
Full date/time pattern (short time) |
Console.WriteLine(String.Format("{0:f}", Now)) |
Monday, August 22, 2005 11:20 PM |
F |
Full date/time pattern (long time) |
Console.WriteLine(String.Format("{0:F}", Now)) |
Monday, August 22, 2005 11:20:55 PM |
g |
General date/time pattern (short time) |
Console.WriteLine(String.Format("{0:g}", Now)) |
8/22/2005 11:20 PM |
G |
General date/time pattern (long time) |
Console.WriteLine(String.Format("{0:G}", Now)) |
8/22/2005 11:20:55 PM |
M or m |
Month day pattern |
Console.WriteLine(String.Format("{0:m}", Now)) |
August 22 |
R or r |
RFC1123 pattern |
Console.WriteLine(String.Format("{0:r}", Now)) |
Mon, 22 Aug 2005 23:20:55 GMT |
s |
Sortable date/time pattern; conforms to ISO
8601 |
Console.WriteLine(String.Format("{0:s}", Now)) |
2005-08-22T23:20:55 |
u |
Universal sortable date/time pattern |
Console.WriteLine(String.Format("{0:u}", Now)) |
2005-08-22 23:20:55Z |
U |
Universal sortable date/time pattern |
Console.WriteLine(String.Format("{0:U}", Now)) |
Tuesday, August 23, 2005 3:20:55 AM |
Y or y |
Year month pattern |
Console.WriteLine(String.Format("{0:y}", Now)) |
August, 2005 |
Any other single character |
Unknown specifier |
Console.WriteLine(String.Format("{0:L}", Now)) |
System.FormatException |
|
Custom DateTime Format Strings
The following table illustrates the output created by applying some custom DateTime format strings to a particular date and time. |
Format Specifier |
Description |
Example (Date: Aug 9, 2005) |
Output |
d, dd |
Day |
Console.WriteLine(String.Format("{0:dd}", Now))
Console.WriteLine(String.Format("{0:M d}", Now))
Console.WriteLine(String.Format("{0:MMM dd}", Now))
|
10
8 10
Aug 10 |
ddd |
Day name (Short) |
Console.WriteLine(String.Format("{0:ddd}",
Now))
Console.WriteLine(String.Format("{0:MMM ddd, yyyy}", Now))
|
Wed
Aug Wed, 2005
|
dddd |
Day name (Full) |
Console.WriteLine(String.Format("{0:dddd}", Now))
Console.WriteLine(String.Format("{0:MMM dddd, yyyy}", Now))
|
Wednesday
Aug Wednesday, 2005 |
f, ff, fff, ffff, ... |
Second's fraction |
Console.WriteLine(String.Format("{0:fff}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss.f}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss.ffff}", Now)) |
859
12:18:37.8
12:18:37.8593 |
g, gg, ggg, gggg, ... |
Era |
Console.WriteLine(String.Format("{0:gg}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss.fff g}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss.fff ggg}", Now))
|
A.D.
12:18:37.859 A.D.
12:18:37.859 A.D. |
h , hh |
Displays the hour for the specified DateTime
in the range 1-12. |
Console.WriteLine(String.Format("{0:hh}", Now))
Console.WriteLine(String.Format("{0:h:m:s}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss}", Now))
|
12
12:18:37
12:18:37 |
H, HH |
Displays the hour for the specified
DateTime in the range 0-23. |
Console.WriteLine(String.Format("{0:HH}", Now))
Console.WriteLine(String.Format("{0:H:m:s}", Now))
Console.WriteLine(String.Format("{0:HH:mm:ss}", Now))
|
00
0:18:37
00:18:37 |
m, mm |
Minutes |
Console.WriteLine(String.Format("{0:mm}", Now))
Console.WriteLine(String.Format("{0:h:m:s}", Now))
Console.WriteLine(String.Format("{0:dd/MM/yyyy hh:mm:ss}", Now))
|
18
12:18:37
10/08/2005 12:18:37 |
M, MM |
Month |
Console.WriteLine(String.Format("{0:MM}", Now))
Console.WriteLine(String.Format("{0:d/M/yy}", Now))
Console.WriteLine(String.Format("{0:dd/MM/yyyy hh:mm:ss}", Now))
|
08
10/8/05
10/08/2005 12:18:37 |
MMM |
Month name (Short) |
Console.WriteLine(String.Format("{0:MMM}",
Now))
Console.WriteLine(String.Format("{0:MMM, yyyy}", Now))
|
Aug
Aug, 2005
|
MMMM |
Month name (Full) |
Console.WriteLine(String.Format("{0:MMMM}",
Now))
Console.WriteLine(String.Format("{0:MMMM, yyyy}", Now))
|
August
August, 2005 |
s, ss |
Second |
Console.WriteLine(String.Format("{0:ss}", Now))
Console.WriteLine(String.Format("{0:h:m:s}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss}", Now))
|
37
12:18:37
12:18:37 |
t, tt |
AM or PM |
Console.WriteLine(String.Format("{0:tt}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss t}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss tt}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss ttt}", Now))
|
AM
12:18:37 A
12:18:37 AM
12:18:37 AM |
y, yy, yyyy |
Year |
Console.WriteLine(String.Format("{0:yy}", Now))
Console.WriteLine(String.Format("{0:MM, yy}", Now))
Console.WriteLine(String.Format("{0:MM, yyy}", Now))
|
05
08, 05
08, 2005 |
z, zz |
Timezone offset (hours) |
Console.WriteLine(String.Format("{0:zz}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss z}", Now))
Console.WriteLine(String.Format("{0:hh:mm:ss zz}", Now))
|
-04
12:18:37 -4
12:18:37 -04 |
zzz |
Timezone offset (hours and minutes) |
Console.WriteLine(String.Format("{0:zzz}",
Now))
Console.WriteLine(String.Format("{0:hh:mm:ss G\MT zzz}", Now))
|
-04:00
12:18:37 GMT -04:00 |
'ABC' or "ABC" |
Literal value |
Console.WriteLine(String.Format("{0: 'Today
is :' MMM, dd yyyy hh:mm:ss tt G\MT zzz}", Now)) |
Today is : Aug, 10 2005 12:18:37 AM GMT
-04:00 |
|
String Encoding
.Net comes with very useful set of classes which you can use to encode various character sets (i.e. Unicode, ASCII, UTF8, UTF7). In .Net you can find all text encoding classes in System.Text name space.
Before we look these classes lets understand different character encoding.
ASCII : ASCII is a code for representing English characters as numbers, with each letter assigned a number from 0 to 127. For example, the ASCII code for uppercase M is 77. Most computers use ASCII codes to represent text, which makes it possible to transfer data from one computer to another.
UNICODE : In computing, Unicode provides an international standard which has the goal of providing the means to encode the text of every document people want to store on computers. In Unicode character set every character is represented using 2 bytes which is enough to represent any character of any language uniquely.
UTF-7 : UTF-7 (7-bit Unicode Transformation Format) is a variable-length character encoding that was proposed for representing Unicode-encoded text using a stream of ASCII characters, for example for use in Internet e-mail messages. UTF-7 is generally not used as a native representation within applications as it is very awkward to process. UTF-7 has its own encoding rules. UTF-7 encoding encodes some ASCII characters as it is and some characters are encoded according to UTF-7 encoding rule. To get detail understanding check the RFC2152 Example:
"Hello, World!" is encoded as "Hello, World!" but "1 + 1 = 2" is encoded as "1 +- 1 = 2" "£1" is encoded as "+AKM-1"
UTF-8 : UTF-8 (8-bit Unicode Transformation Format) is a lossless, variable-length character encoding for Unicode. It uses groups of bytes to represent the Unicode standard for the alphabets of many of the world's languages. UTF-8 is especially useful for transmission over 8-bit Electronic Mail systems. It uses one to four bytes per character, depending on the Unicode symbol. For example, only one UTF-8 byte is needed to encode the 128 US-ASCII characters in the Unicode range U+0000 to U+007F.
The System.Text namespace offers an Encoding class. Encoding is an abstract class, so you can’t instantiate it directly. However, it does provide a range of methods and properties for converting arrays and strings of Unicode characters to and from arrays of bytes encoded for a target code page.
String Encoding Classes |
ASCII |
Encodes Unicode characters as single, 7-bit
ASCII characters. This encoding supports only character values between
U+0000 and U+007F |
BigEndianUnicode |
Encodes each Unicode character as two
consecutive bytes, using big endian (code page 1201) byte ordering. |
Unicode |
Encodes each Unicode character as two
consecutive bytes, using little endian (code page 1200) byte ordering. |
UTF7 |
Encodes Unicode characters using the UTF-7
encoding. (UTF-7 stands for UCS Transformation Format, 7-bit form.) This
encoding supports all Unicode character values and can be accessed as
code page 65000. |
UTF8 |
Encodes Unicode characters using the UTF-8
encoding. (UTF-8 stands for UCS Transformation Format, 8-bit form.) This
encoding supports all Unicode character values and can be accessed as
code page 65001. |
|
Working with ASCII String and Byte Array (String->Array, Array->String)
This example shows you how to convert VB String to Byte Array and Byte Array to String. In this example ASCII encoding is used so each string character will be encoded in 1 byte and stored into byte array. To encode VB.net string into ASCII Byte array use Encoding.ASCII.GetBytes method . To get string back from ASCII Byte Array use Encoding.ASCII.GetString method.
If your have any unicode characters in your string or array which requires more than 1 byte for storage then consider other Encoding classes (i.e. Encoding.Unicode, Encoding.UTF7, Encoding.UTF8). |
Click here to copy the following block | Sub ASCIIDemo() Dim strDemo1 As String = "ABC" Dim str As String
Dim arr() As Byte
arr = System.Text.Encoding.ASCII.GetBytes(strDemo1) Console.WriteLine("VB.net string(Unicode) converted to ASCII Byte Array") PrintArray(arr)
Console.WriteLine("ASCII Byte Array converted to string") str = System.Text.Encoding.ASCII.GetString(arr) Console.WriteLine(str) End Sub
Sub PrintArray(ByVal arr() As Byte) Dim i As Integer If arr.GetUpperBound(0) >= 0 Then For i = 0 To arr.GetUpperBound(0) Console.Write("{0,-4}", arr(i).ToString) Next Console.WriteLine() End If End Sub |
VB.net string(Unicode) converted to ASCII Byte Array
65 66 67
ASCII Byte Array converted to string
ABC |
Working with Unicode String and Byte Array (String->Array, Array->String)
As we all know that VB.net stores each string character using 2 bytes which means you can store any international (Unicode) character in VB.net string. Encoding.Unicode class can help you to convert unicode string to byte array and bytearray to unicode string. In the following example 3 unicode strings are declared and then |
Click here to copy the following block | Sub UnicodeDemo()
Dim unicodeString As String = "Pi (" & ChrW(928) & ") and Sigma (" & ChrW(931) & ")." Dim arr() As Byte Dim strFromByteArr As String
MsgBox("Original string:" & vbCrLf & unicodeString)
arr = System.Text.Encoding.Unicode.GetBytes(unicodeString) PrintArray(arr)
strFromByteArr = System.Text.Encoding.Unicode.GetString(arr) MsgBox("String from Byte Array:" & vbCrLf & strFromByteArr) End Sub
Sub PrintArray(ByVal arr() As Byte) Dim i As Integer If arr.GetUpperBound(0) >= 0 Then For i = 0 To arr.GetUpperBound(0) Console.Write("{0,-4}", arr(i).ToString) Next Console.WriteLine() End If End Sub |
80 0 105 0 61 0 160 3 32 0 83 0 105 0 103 0 109 0 97 0 61 0 163 3
|
StringBuilder Class
So far we have seen how to work with string class. We know that in VB.net strings are immutable means any change to string creates a new copy and removes old copy. This is definitely performance hit if you are doing several string operations in short time specially appending strings, replacing strings etc. To get best performance with large string operation you can use System.Text.StringBuilder class. Lets look at a simple comparison between String class and StringBuilder class to get more idea (You will say wow when you look at the result). |
Click here to copy the following block | Dim str As String Dim i As Integer Dim sb As New System.Text.StringBuilder Dim dtStart As DateTime
dtStart = Now
For i = 1 To 25000 str = str & " Some test string " Next Console.WriteLine("String append took " & Now.Subtract(dtStart).TotalSeconds & " seconds to append 25000 strings")
dtStart = Now
For i = 1 To 1550000 sb.Append(" Some test string ") Next Console.WriteLine("StringBuilder append took " & Now.Subtract(dtStart).TotalSeconds & " seconds to append 1550000 strings") |
String append took 25.59375 seconds to append 25000 strings
StringBuilder append took 0.40625 seconds to append 1550000 strings
|
So difference itself tells you about StringBuilder performance compared to String class. Lets look at few more properties and methods of StringBuilder class. |
Click here to copy the following block | Sub StringBuiderDemo() Dim strFName, strLName, strPhone As String Dim sb As New System.Text.StringBuilder
sb.Append("<HTML><HEAD><TITLE>AAAA StringBuilder Demo</TITLE></HEAD><BODY>" & vbCrLf) sb.Append("<TABLE>" & vbCrLf)
sb.AppendFormat("<TR><TD>{0}</TD><TD>{1}</TD><TD>{2}</TD></TR>{3}", "FirstName", "LastName", "Phone", vbCrLf) sb.AppendFormat("<TR><TD>{0}</TD><TD>{1}</TD><TD>{2}</TD></TR>{3}", "Nayan", "Patel", "770-123-4567", vbCrLf)
sb.Append("</TABLE>" & vbCrLf) sb.Append("</BODY></HTML>")
Dim search As String Dim pos As Integer search = "AAAA" pos = sb.ToString.IndexOf("AAAA") sb.Remove(pos, search.Length)
sb.Replace("Phone", "Cell")
Console.WriteLine("sb.Char(0) : " & sb.Chars(0)) Console.WriteLine("sb.Char(3) : " & sb.Chars(3))
Console.WriteLine("sb.MaxCapacity : " & sb.MaxCapacity) Console.WriteLine("sb.Length : " & sb.Length) Console.WriteLine("sb.ToString : " & sb.ToString) End Sub |
sb.Char(0) : <
sb.Char(3) : M
sb.MaxCapacity : 2147483647
sb.Length : 213
sb.ToString : <HTML><HEAD><TITLE> StringBuilder Demo</TITLE></HEAD><BODY>
<TABLE>
<TR><TD>FirstName</TD><TD>LastName</TD><TD>Cell</TD></TR>
<TR><TD>Nayan</TD><TD>Patel</TD><TD>770-123-4567</TD></TR>
</TABLE>
</BODY></HTML> |
|
|
|
Submitted By :
Nayan Patel
(Member Since : 5/26/2004 12:23:06 PM)
|
|
|
Job Description :
He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting. |
View all (893) submissions by this author
(Birth Date : 7/14/1981 ) |
|
|