Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Mindcracker MVP Summit 2012
Search :       Advanced Search »
Home » Strings & Arrays » Working with Strings in VB.NET

Working with Strings in VB.NET

This tutorial explains how to represent strings in .NET using VB.NET and how to work with them with the help of .NET class library classes.

Author Rank :
Page Views : 584737
Downloads : 654
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
stringsInVBNetCode.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 



.NET Framework library provides classes to work with strings and these classes are common to all .NET language including C# and VB.NET.
 
In this tutorial, I will discuss how to use these classes to work with strings using VB.NET.

Comparing Strings.

The Compare method compares two strings and returns an integer value. The return value of Compare method can be less than zero, greater than zero or equals to zero.

Value Meaning.

Less than zero When first string is less than second.
Zero When both strings are equal.
Greater than zero When first string is greater than zero.

The following code compares two strings and return results on the System console.

' Comparing two strings
'===============================================
Dim str1 As String = "ppp"
Dim str2 As String = "ccc"
Dim res As Int16 = String.Compare(str1, str2)
Console.WriteLine("First result:" + res.ToString())
str2 = "ttt"
res = String.Compare(str1, str2)
Console.WriteLine("Second result:" + res.ToString())
str1 = "ttt"
res = String.Compare(str1, str2)
Console.WriteLine("Third result:" + res.ToString())
'===============================================

The CompareTo method is an instance method. It compares a value (either a string or on object) with a string instance. Return values of this method are same as the Compare method. The following source code compares two strings.

' CompareTo Method
Dim str As String = "kkk"
Console.WriteLine(str.CompareTo(str1))

Copy and Concatenating Strings.

The Concat method adds strings (or objects) and returns a new string. Using Concat method, you can add two strings, two objects and one string and one object or more combinations of these two.

The following source code concatenate two strings.

Dim str1 As String = "ppp"
Dim str2 As String = "ccc"
Dim strRes As String = String.Concat(str1, str2)
Console.WriteLine(strRes)

The following source code concatenates one string and one object.

Dim obj As Object = 12
strRes = String.Concat(str1, obj)
Console.WriteLine(strRes)

The Copy method copies contents of a string to another. The Copy method takes a string as input and returns another string with the same contents as the input string. For example, the following code copies str1 to strRes.

strRes = String.Copy(str1)
Console.WriteLine("Copy result :" + strRes)

The CopyTo method copies a specified number of characters from a specified position in this instance to a specified position in an array of characters. For example, the following example copies contents of str1 to an array of characters. You can also specify the starting character of a string and number of characters you want to copy to the array.

Dim str1 As String = "pp"
Dim chrs(2) As Char
str1.CopyTo(0, chrs, 0, 2)
Console.WriteLine(chrs(0) + chrs(1))

The Clone method returns a new copy of a string in form of object. The following code creates a clone of str1.

Dim str1 As String = "ppp"
Dim objClone As Object = str1.Clone()
Console.WriteLine("Clone :" + objClone.ToString())

The Join method is useful when you need to insert a separator (String) between each element of a string array, yielding a single concatenated string. For example, the following sample inserts a comma and space (", ") between each element of an array of strings.

Dim str1 As String = "ppp"
Dim str2 As String = "ccc"
Dim str3 As String = "kkk"
Dim allStr() As String = New String() {str1, str2, str3}
Dim strRes As String = String.Join(", ", allStr)
Console.WriteLine("Join Results: " + strRes)

Adding, Removing and Replacing Strings.

The Insert method inserts a specified string at a specified index position in an instance. For example, the following source code inserts "bbb" after second character in str1 and the result string is "pbbbpp".

Dim str1 As String = "ppp"
Dim strRes As String = str1.Insert(2, "bbb")
Console.WriteLine(strRes.ToString())

The Remove method deletes a specified number of characters from a specified position in a string. This method returns result as a string. For example, the following code removes three characters from index 3.

Dim s As String = "123abc000"
Console.WriteLine(s.Remove(3, 3))

The Replace method replaces all occurrences of a specified character in a string. For example, the following source code replaces all p character instances of str1 with character l and returns string "lll".

Dim str1 As String = "ppp"
Dim repStr As String = str1.Replace("p", "l")
Console.WriteLine("Replaced string:" + repStr.ToString())

The Split method separates strings by a specified set of characters and places these strings into an array of strings. For example, the following source code splits strArray based on ',' and stores all separated strings in an array.

Dim str1 As String = "ppp"
Dim str2 As String = "ccc"
Dim str3 As String = "kkk"
Dim strAll3 As String = str1 + ", " + str2 + ", " + str3
Dim strArray() As String = strAll3.Split(",")

Uppercase and Lowercase.

The ToUpper and ToLower methods convert a string in uppercase and lowercase respectively. These methods are easy to use. The following code shows how to use ToUppler and ToLower methods.

Dim aStr As String = "adgas"
Dim bStr As String = "ABNMDWER"
Dim strRes As String = aStr.ToUpper()
Console.WriteLine("Uppercase:" + strRes.ToString())
strRes = bStr.ToLower()
Console.WriteLine("Lowercase:" + strRes.ToString())

Formatting Strings.

You can use the Format method to create formatted strings and concatenate multiple strings representing multiple objects. The Format method automatically converts any passed object into a string.

For example, the following code uses integer, floating number and string values and format them into a string using the Format method.

Listing 1. Using Format method to format a string.

Dim val As Int16 = 7
Dim name As String = "Mr. John"
Dim num As Double = 45.06F
Dim str As String = String.Format("Days Left : {0}. Current DataTime: {1:u}. \n String: {2}, Float: {3}", val, DateTime.Now, name, num)
Console.WriteLine(str)

The output of Listing 1 is shown Figure 1.



Figure 1.

Trimming and Removing Characters from Strings.

The String class provides Trim, TrimStart and TrimEnd methods to trim strings. The Trim method removes white spaces from the beginning and end of a string. The TrimEnd method removes characters specified in an array of characters from the end of a string and TrimStart method removes characters specified in an array of characaters from the beginning of a string.

You can also use the Remove method to remove characters from a string. The Listing 2 code shows how to use these methods.

Dim str As String = " C# "
Console.WriteLine("Hello{0}World!", str)
Dim trStr As String = str.Trim()
Console.WriteLine("Hello{0}World!", trStr)
str = "Hello World!"
Dim chArr() As Char = {"e", "H", "l", "o", " "}
trStr = str.TrimStart(chArr)
Console.WriteLine(trStr)
str = "Hello World!"
Dim chArr1() As Char = {"e", "H", "l", "o", " "}
trStr = str.TrimEnd(chArr1)
Console.WriteLine(trStr)
Dim MyString As String = "Hello Delta World!"
Console.WriteLine(MyString.Remove(5, 10))

Padding Strings.

The PadLeft and PadRight methods can be used to pad strings. The PadLeft method right-aligns and pads a string so that its rightmost character is the specified distance from the beginning of the string. The PadRight method left-aligns and pads a string so that its rightmost character is a specified distance from the end of the string. These methods return new String objects that can either be padded with empty spaces or with custom characters. Listign 3 shows how to use these methods.

Listing 3. Using padding methods.

Dim str1 As String = "My String"
Console.WriteLine(str1.PadLeft(20, "-"))
Dim str2 As String = "My String"
Console.WriteLine(str2.PadRight(20, "-"))

The output of Listing 3 is shown in Figure 2.



Figure 2.

Using StringBuilder Class.

The StringBuilder class represents a mutable string of characters. It's called mutable because it can be modified once it has been created by using Append, Insert, Remove, and Replace methods.

Note: When there are multiple concatenation operations are involved with strings, for performance reasons it is recommended to use StringBuilder instead of String.

The StringBuilder class is defined in the System.Text namespace. Before you use the StringBuilder class make sure you add the following line in your application:

imports System.Text

Table 2 describes the StringBuilder class properties.

Property Description
Capacity Represents the maximum number of characters that can be contained in the memory allocated by the current instance.
Chars Represens the character at the specified position.
Length Represents the number of characters.
MaxCapacity Returns the maximum capacity.

Table 2. The StringBuilder class properties.

Table 3 describes the StringBuilder class methods.

Method Description
Append Appends a string at the end of this string.
AppendFormat Appends a formatted string.
EnsureCapaciry Ensures that the capacity of string is as specified value.
Inserts Inserts string at the specified position.
Remove Removes a range of characters from the string.
Replace Replaces all occurrences of a character from the string.

Table 3. The StringBuilder class methods.

Using StringBuilder properties and methods is pretty simple. Listing 4 uses StringBuilder class to append, insert, remove and replace characters of a string.

Listing 4. Using StringBuilder class to append, add, replace and remove characters.

Dim builder As StringBuilder = New StringBuilder("Hello C# World!", 20)
Dim cap As Int16 = builder.EnsureCapacity(55)
builder.Append(". This is a class test.")
Console.WriteLine(builder)
builder.Insert(26, " String Builder")
Console.WriteLine(builder)
builder.Remove(5, 9)
Console.WriteLine(builder)
builder.Replace("!", "?")
Console.WriteLine(builder)
Console.WriteLine("Length of string is:" + builder.Length.ToString())
Console.WriteLine("Capacity of string is:" + builder.Capacity.ToString())

The output of Listing 4 is shown in Figure 3.



Figure 3.

About Source Code:

Download and unzip the attached vb files. Create a Windows console application using VS.NET and type the code. Make sure you add reference to the System.Text references when compiling StringBuilder sample.

Summary.

In this article you saw some methods and properties of String class. I also discussed some methods of String, basics of StringBuilder class and how to use StringBuilder class to add, insert, append and remove items from strings.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
vb.net by satheesh kumar On January 28, 2008
string builder programs doesn't work.when compiling it displays compiling errors.
Reply | Email | Modify 
array of stringbuilder by prasanna On March 3, 2010

how to write array of stringbuilder?

Reply | Email | Modify 
thanks by zaz On May 26, 2010

d

Reply | Email | Modify 
urgent requirement by sonia On June 16, 2010
Hi,
I have xls sheet,
i want code to replace one string to blank.pls help me out soon
Reply | Email | Modify 
Re: urgent requirement by krishna On December 1, 2010

code for replacing string to blank in excel

      =replace("welcome to",9,2," ")

here I remove the last two character(9 th position to 2 characters) to be blanked.

Reply | Email | Modify 
Remove space between positions on a flat file fixed format by massanda On September 24, 2010
Hello,

could you please advise on how to remove spaces between position 7394 and 248045?

many thanks,

Massanda
Reply | Email | Modify 
Count replacements for .Replace by Steve On October 2, 2010
Is there a way to count the number of replacements when globally replacing one string with another in VB.NET?
Reply | Email | Modify 
VB Concatenate by Sandra On July 21, 2011
Hi I'm trying to write a code to concatenate fields and I seem to be having a problem The guidelines are as follows "Write the code for the “Put Together” button click event. The subroutine should call a function PutFieldsTogether. The PutFieldsTogether function should get the text from all the txtField# textboxes and create a string by concatenating the fields together with comma&space in between each field. The PutFieldsTogether function should return this string. The “Put Together” button click subroutine should then update the text in txtRecord with the returned string. The “Put Together” button click subroutine should also clear the txtField# textboxes." Here's the what I have written but it won't run Private Sub btnPutTogether_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPutTogether.Click Dim str1 As String = txtField1.Text Dim str2 As String = txtField2.Text Dim str3 As String = txtField3.Text Dim str4 As String = txtField4.Text Dim str5 As String = txtField5.Text Dim str6 As String = txtField6.Text Dim strJoinRecord As String strJoinRecord = PutFieldsTogether(str1, str2, str3, str4, str5, str6) End Sub Private Function PutFieldsTogether(ByVal str1 As String, ByVal str2 As String, ByVal str3 As String, ByVal str4 As String, ByVal str5 As String, ByVal str6 As String) As String Dim strJoinRecord As String Dim Fields() As String = New String() {str1, str2, str3, str4, str5, str6} strJoinRecord = String.Join(",", Fields) strJoinRecord = txtRecord.Text Return strJoinRecord End Function
Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.