Important alert: (current site time 4/16/2014 8:50:47 AM EDT)
 

article

_ A String manipulation example in VB.NET, EQUIVALENTS: Len, Mid, Replace, InStr, UCase, Split etc _

Email
Submitted on: 3/25/2002 9:21:32 AM
By: Jon Barker  
Level: Beginner
User Rating: By 90 Users
Compatibility: VB.NET
Views: 694858
(About the author)
 
     A string manipulation example in VB.NET. Are ALL covered in the tutorial, using PURE VB.NET STRING MANIPULATION TEQNIQUES Commands and equivilents Len = .Length, Mid = .SubString, Replace = .Replace, InStr = .IndexOf, UCase = .ToUpper, LCase = .ToLower, Split = .Split, Join = .Join, Enjoy! tHe_cLeanER

 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
  1. You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
				String manipulation in VB.NET. Equivalents of Len, Mid, Replace, InStr, etc.
Title:
String manipulation examples in VB.NET. Equivalents of Len, Mid, Replace, InStr, UCase, Split, etc.

Description:
The following functions and procedures can be used to manipulate general strings, and more or less do whatever you like with them! If you get stuck, look at the bottom of this tutorial for contact information.

<-- --> VB 6 Commands and equivalents:
Len = .Length
Mid = .SubString
Replace = .Replace
InStr = .IndexOf
UCase = .ToUpper
LCase = .ToLower
Split = .Split
Join = .Join
1. Getting the length of a string or variable

This produces a messagebox containing the number of characters in textbox1. This will be in the form of a numerical value.

MsgBox(Textbox1.Text.Length)
This code produces a messagebox saying "22" because 'strText' is 22 characters long.
Dim StrText As String
Dim r As Integer
 
StrText = "How long is this text?"
r = StrText.Length
MsgBox(r)
2. The following code is used to get a part of a string. Useful for cutting off bits that aren't needed throughout the rest of the code. It is called the SubString function. It accepts the start position, and the number of characters you wish to read from the start position.

The value of 'r' below will be 'to the world' because we are cutting off the first 8 characters. We have specified no number of characters to read, so 'r' will read from the 9th character to the end.

Dim r As String = "Welcome to the world"
r = r.Substring(8)
 
MsgBox(r)
In the example below, we make the read length 6. Now, the value of 'r' be be 'to the', because we start reading at 8 characters into the string, and stop reading 8 + 6 characters into the string.
Dim r As String = "Welcome to the world"
r = r.SubString(8, 6)
MsgBox(r)
3. If you wish to search the text for a particular word, then you will use the IndexOf(Find word, StartPosition) function. This function is very customisable to your needs, and so has a lot of optional extras that can be added, but in the interests of simplicity, I'll leave these off the tutorial. The IndexOf command returns its value as an integer (number) as a place where it found the string in the search text.

This code starts at the beginning of 'The weather today is reasonably warm and sunny', because we didn't give a start position, and searches for the word 'warm' in it. If it does not find the word warm in the string, then it will return the value as 0, and you get a message saying '0'. However, if it finds the word, then it returns a number saying where it found the start of the word. In this case, you would see a messagebox saying '32' because the 'w' of warm is 32 characters into the string.

Dim r As String = "The weather today is reasonably warm and sunny"
r = r.IndexOf("warm")
 
MsgBox(r)
If you wish to make a simple search program, to find searchword TextBox2.Text in the string TextBox1.Text, then this is how you would go about doing it:
Dim r As Integer
TextBox1.Text = "Welcome to the grand parade"
TextBox2.text = "grand"
r = TextBox1.Text.IndexOf(TextBox2.Text)
 If r > 0 Then
MsgBox("Found word, " & r & " characters into the search string.") 
 Else 
MsgBox("Sorry, could not find the search text") 
 End If
If the above code works correctly (and it should :) then you should get a message box telling you the word was found 15 chars into the search string.

4. Next, is .Replace(search for text, replace with text). It is used to search through a string, and replace certain words or characters with other ones. The Replace function returns the text that it has replaced.

This code would produce a message replacing the word 'fool' with 'brave bloke', and therefore will look like this: 'Only a brave bloke goes
outside in the cold without a coat on'.

Dim i As String = "Only a fool goes outside in the cold without a coat on"
i = i.Replace("fool", "brave bloke")
 
MsgBox(i)
Another example of this use, is to remove a swearword from a sentence etc, as follows: This code searches through TextBox1.text, and replaces all instances of 'oh my god', with 'oh my goodness', then returns the text back into TextBox1.text, without the cursing.
TextBox1.Text = "I was walking through the park when I realised I was insane. 'oh my god', i said out loud"
 
TextBox1.Text = TextBox1.Text.Replace("oh my god", "oh my goodness")
To define the point where the Replace function starts searching the string, include the number of characters you wish to start from in the command. Not only does this example only replace the second 'e' with an 'E', it cuts off the string from the point you specify. The outcome of the line above would be 'TEst'.
MsgBox(Replace("Test Test", "e", "E", 6))
5. Converting a string to uppercase / lowercase

This is useful for making sure that if a user types something in uppercase (capitals) then it will still comply with something in your code that is lowercase. For example, if you are making a text adventure, and the user is given a choice of left or right, and they type LEFT, as VB is case sensitive, your program wouldn't accept their answer, and tell them it was invalid! To combat this, you use the string.ToUpper or string.ToLower commands

To make a sentence uppercase, you use the following:

Dim r as String
r = "Isn't the internet FABULOUS!"
r = r.ToUpper
 	
TextBox1.Text = r
TextBox1 will now contain the words 'ISN'T THE INTERNET FABULOUS!'
Or to convert to lowercase, use the following:
Dim r as String
r = "Isn't the internet FABULOUS!"
r = r.ToLower
TextBox1.Text = r
TextBox1 will now contain the words 'isn't the internet fabulous'

6. Reversing the order of characters in a string.

If you wish to flip around the front and back end of a string, then the StrReverse(string) is for you. It is used in the following way. This would pop up a message saying 'esabatad egral rehtar a si CSP'. I'm not quite sure why you'd want to use this function, but may be useful to know!

MsgBox(StrReverse("PSC is a rather large database"))
7. Comparing strings in terms of ASCII values / Case.

The String.Compare function seems reasonably useful in this field. It is used in context String.Compare(string1, string2). This function returns its value as an integer, specifying what it found. In this case, you would get TextBox1.Text giving you the value 1, because tHe_cLeanER is greater in ASCII value than THE_CLEANER.

TextBox1.Text = String.Compare("tHe_cLeanER", "THE_CLEANER")
If TextBox1.Text = -1 Then 
 MsgBox("String 1 is less than string 2")
End If
 
If TextBox1.Text = 0 Then 
 MsgBox("String 2 is equal to string 1")
End If
 
If TextBox1.Text = 1 Then 
 MsgBox("String 1 is greater than string 2")
End If
 
If TextBox1.Text = "" Then 
 MsgBox("String 1 and / or string two is null")
End If
8. Creating arrays with the Split(split-character) function.

This function allows you to create a one-dimensional array, by splitting a string by recognizing a certain character, then putting any text after the character on a new line in the array.
This code will pop up a message box For each item in the array, which is 4. Note that the first line is infact 0.

Dim i As String = "Line 0|Line 1|Line 2|Line 3"
Dim a() As String
Dim j As Integer
a = i.Split("|")
For j = 0 To a.GetUpperBound(0)
 MsgBox(a(j))
Next
Another use of this function could be for getting all the lines from a multiline text box as follows: This will pull all lines of the text box, and use them to create an array, which is stored in r. You extract these values from the array by selecting where in the array you wish to look. The look-in-line is defined after the r, in brackets. Example: Msgbox r(3) would pull the FORTH line of the array that is being held in r. Msgbox r(5) would pull the 6th line being held in the array.
Dim a() As String
Dim j As Integer
a = TextBox1.Text.Split(Lf)
 
For j = 0 To a.GetUpperBound(0)
 MsgBox(a(j))
Next
9. Joining an array back into one string. Uses the .Join(split character, array) function.

If you have an array, and wish to compile it back into one string, then the Join function (Which is the opposite of the Split function) is the one to use. This code will put back together an array into a string, separating different lines in the array with the specified character. In this case, I used the carriage return char, which is the equivalent of pressing Enter. The above code will compile an array created from a multiline text box. It will work fine with the previous procedure.
Note: this will only work if 'a' contains an array. See previous to create an array.

Dim r As String
Dim a() As String
 
r = String.Join(vbCrLf, a)
MsgBox(r)
Submitted by: tHe_cLeanER
Thanks to VBnet4Apps for code formatting and CSS.
E-mail: Contributor


Other 14 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments

3/26/2002 2:29:00 AMOmer

I thought you made these functions yourself :s
(If this comment was disrespectful, please report it.)

 
3/26/2002 2:29:56 AMMohammad Omer Sadiq

i thought you made these functions yourself in .NET
(If this comment was disrespectful, please report it.)

 
3/26/2002 4:19:51 AMtHe_cLeanER

Nah, these are the ones that already exist. I just used the title with all the old string manipulation commands so that people would be able to search for the tutorial more easily. All the commands I just taught you exist in VB.NET
(If this comment was disrespectful, please report it.)

 
3/26/2002 10:15:58 AMroswellevent

Good Job!
(If this comment was disrespectful, please report it.)

 
4/12/2002 3:05:11 AM...tHe_cLeanER... / jB

OK.. i sorta got the guist of what you were saying spanish bloke :) i've updated the tutorial and sorted out the problem :)
(If this comment was disrespectful, please report it.)

 
4/18/2002 11:48:03 AMhi,

how about the left(xxx,3) or right(xxx,5) funcytion in vb.net
(If this comment was disrespectful, please report it.)

 
4/18/2002 1:40:33 PM...tHe_cLeanER... / jB

hi there, 'hi', as far as im aware, there isnt an equivilent to those functions, although Left and Right still work in VB.NET :)
(If this comment was disrespectful, please report it.)

 
4/18/2002 2:38:55 PMThraka

It's not exactly efficent to use that way in .NET compaired to VB6. The string class now destroys itself and recreats it everytime you change its value. So doing something like
dim sval as string
sval = "ABC" :
sval = sval.concat(sval,"DEF")
The second line actually destorys the sval object and recreates it. Suggest using the StingBuilder class instead. this creates a buffer that holds string values and you can miniplulate it just like before in vb6 (system.text.stringbuilder)
(If this comment was disrespectful, please report it.)

 
4/23/2002 9:56:44 AMtHe_cLeanER

thanks for the feedback thraka, certainly for advanced users that will be usefull, but this tutorial was intended for beginners :)
(If this comment was disrespectful, please report it.)

 
5/19/2002 5:40:48 PMNoodlez

...how the hell do you use Left() and Right()
(If this comment was disrespectful, please report it.)

 
6/19/2002 2:51:47 AMwEnGwAsHeRe

thanks for the info
(If this comment was disrespectful, please report it.)

 
6/20/2002 12:41:06 PMLewis Moten

Interesting. VB.Net is moulding itself simular to javascript. This could prove to be confusing at first.
(If this comment was disrespectful, please report it.)

 
8/13/2002 9:56:38 AMBjarni

Where is IsNull ??
(If this comment was disrespectful, please report it.)

 
8/13/2002 9:56:51 AMBjarni

Where is IsNull() ??
(If this comment was disrespectful, please report it.)

 
9/5/2002 5:44:47 AM

Great Job Cleaner
(If this comment was disrespectful, please report it.)

 
1/3/2003 1:43:15 AMUDMX IOCP

good job... saved me sometime... lolz 5 globes.. just started learnin..
(If this comment was disrespectful, please report it.)

 
1/3/2003 1:44:03 AMUDMX IOCP

btw.. this page's textcolor is orange...lolz
(If this comment was disrespectful, please report it.)

 
1/3/2003 2:41:08 AMtHe_cLeanER

lol yeh, the orange is because of the CSS file i used :D
(If this comment was disrespectful, please report it.)

 
1/21/2003 10:16:23 AM

The split function is not exactly like your description. The .NET split function can only split using a single character as the delimiter. In VB6, you can use a multi-character delimiter. This means you won't be able to split using the vbCRLF as you describe in your example.
(If this comment was disrespectful, please report it.)

 
1/22/2003 1:34:58 PMtHe_cLeanER

code updated, thanks [blank]
(If this comment was disrespectful, please report it.)

 
3/20/2003 11:43:28 PM

do you know of a replacement for the vb string$ function.
(If this comment was disrespectful, please report it.)

 
3/22/2003 12:29:40 AM

I found the vb6 String$(25,"-") replacement in vb.net is
Dim Buffer As String
Buffer = New String(CChar("-"), 25)
I hope this helps others.

(If this comment was disrespectful, please report it.)

 
5/28/2003 5:14:35 PM

Barkie-boy... you rock my world. Without this I would never have been able to break into the nuclear missile warheads that I booby-trapped in the centre of Woking... MWAH HA HA HA
Seriously though good tutorial, Tony the Tiger
(If this comment was disrespectful, please report it.)

 
6/17/2003 1:56:23 PMDan Fogelberg

LEFT example
s = Left(
(If this comment was disrespectful, please report it.)

 
6/17/2003 2:45:47 PMDan Fogelberg

LEFT example
s = Left("Hello World", 5)  ' returns "Hello"
is equivalent to
s = "Hello World".Substring(0, 5)  ' returns "Hello"

RIGHT example
s = Right(Hello World", 5)  ' returns "World"
is equivalent to
s = "Hello World"
s1 = s.Substring(s.Length - 5)  ' returns "World"

(If this comment was disrespectful, please report it.)

 
6/19/2003 7:20:11 AMMy Address

Good help for me!
(If this comment was disrespectful, please report it.)

 
11/16/2003 9:55:13 PM

Nice, Very nice indeed.
(If this comment was disrespectful, please report it.)

 
2/20/2004 3:26:31 AM


(If this comment was disrespectful, please report it.)

 
2/20/2004 3:31:54 AM

"Hello".IndexOf("Z") <-- turns -1
"Hello".IndexOf("H") <-- turns 0


(If this comment was disrespectful, please report it.)

 
2/21/2004 2:10:56 PM

i was wondering how one would go about returning a string in proper case without using the built-in function for proper case?? capitalize the 1st letter of each word and leave the remainder in lowercase and allow multiple entries
(If this comment was disrespectful, please report it.)

 
3/4/2004 8:12:25 AMl

thank you, this helps much
(If this comment was disrespectful, please report it.)

 
9/17/2004 12:38:30 PM

Nice.... Can you tell me how to search a text file (using VB.NET) for every instance of a string (mystring =
(If this comment was disrespectful, please report it.)

 
9/17/2004 12:42:29 PM

(the board cut my post off)
And grab the instances of those strings
along with the trailing 16 chars after
each instance? Output into a variable or another txt file.
Thanks

(If this comment was disrespectful, please report it.)

 
9/24/2004 5:27:16 AM

could anyone tell me the answer about this question:

string1=
(If this comment was disrespectful, please report it.)

 
9/24/2004 5:28:41 AM

could anyone tell me the answer about
this question:
string1="Robert is 7 years old!"
string2="jackson is 21 years old!"
use any single function to get the
numbers from the strings. Enjoy it.
notice: There are always the same
amount of letters from right side of
the string.
(If this comment was disrespectful, please report it.)

 
1/26/2005 9:04:30 PMshah

two words from me..cool dude!
(If this comment was disrespectful, please report it.)

 
3/27/2005 5:10:16 PMimageofgod

I was just searching through all the articles/tuts on here; although I know this info already i still think its informative. Thanks for your time. If the time were right I'd give you 5globes.
(If this comment was disrespectful, please report it.)

 
4/3/2005 6:56:34 AMNimphious Faran Draco

For anyone who needs something like VB6's Left and Right, I've made these two little functions. Check it:
(If this comment was disrespectful, please report it.)

 
4/3/2005 6:57:17 AMNimphious Faran Draco

Private Function strLeft(ByVal vString As String, ByVal vLength As Integer) As String
strLeft = vString.Substring(0, vLength)
End Function
Private Function strRight(ByVal vString As String, ByVal vLength As Integer) As String
strRight = vString.Substring(vString.Length - (vString.Length - vLength), vLength)
End Function
(If this comment was disrespectful, please report it.)

 
4/3/2005 6:59:29 AMNimphious Faran Draco

Sorry, I forgot to do the HTML, here it is properly:

  Private Function strLeft(ByVal vString As String, ByVal vLength As Integer) As String
  strLeft = vString.Substring(0, vLength)
  End Function
  Private Function strRight(ByVal vString As String, ByVal vLength As Integer) As String
  strRight = vString.Substring(vString.Length - (vString.Length - vLength), vLength)
  End Function
(If this comment was disrespectful, please report it.)

 
4/3/2005 7:00:04 AMNimphious Faran Draco

GAH, Well you get the idea. -_-' I hope
(If this comment was disrespectful, please report it.)

 
4/17/2005 3:48:38 PMTravis Howle

To use the left you can use Microsoft.VisualBasic.Left(str, n) or use Microsoft.VisualBasic.Right(str, n). It might be easier to just import the namespace also.
(If this comment was disrespectful, please report it.)

 
5/6/2005 5:50:06 AM

Excelent, please look ahead
(If this comment was disrespectful, please report it.)

 
5/27/2005 3:13:29 PMAli

why the Articles and tutorail are onlyin V.B.we want the same Articles and tutorail in c#..etc
Thank you

(If this comment was disrespectful, please report it.)

 
5/29/2005 11:10:38 PMfrancis matias durian

great tutorial of string manipulation for beginners like me!!!
(If this comment was disrespectful, please report it.)

 
9/12/2005 4:53:09 PMBlaine

Get All Numbers in a string (This is a year over due for someone - but for anyone else that needs....)

Shared Function GetNumbersOnly(ByVal s As String) As String
Dim i As Int32
Dim r As String = ""
For i = 0 To (s.Length - 1)
If Char.IsDigit(s.Chars(i)) Then
r &= s.Chars(i)
End If
Next
Return r
End Function
(If this comment was disrespectful, please report it.)

 
11/23/2005 8:38:56 AMfatih adiguzel

that was cool. really everyting that I need about the functions were here. good work, really deserved 5 poins
(If this comment was disrespectful, please report it.)

 
1/30/2006 4:58:49 PMBill Wilkinson

In the section on IndexOf, you state that if the substring is not found, the function returns zero.

Wrong. Read:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frl rfsystemstringclassindexoftopic2.asp

It
returns -1. I see this has been reported before. Could you please change the article to correct the code?


(If this comment was disrespectful, please report it.)

 
1/30/2006 4:59:31 PMBill Wilkinson

In section 7, you coded:
TextBox1.Text = String.Compare("tHe_cLeanER", "THE_CLEANER")
If TextBox1.Text = -1 Then
... etc. ...

If a user (properly, in my opinion) codes
OPTION STRICT ON
then all of that stuff would fail.

String.Compare returns an *INTEGER*, and the only reason that code works is that VB.NET still allows sloppy conversions from string to number and back when OPTION STRICT ON is not used. Here, the integer is converted to a string in order to store it into the .TEXT string value. And then it has to be converted *AGAIN* when it is compared to the -1, 0, and 1 values.

Also, the last part there is doing nothing:
If TextBox1.Text = "" Then
That can never happen. If you read the specifications for String.Compare, you will see that Nothing values do *NOT* create a Nothing result:
http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemstringclasscomp aretopic1.asp?frame=true


(If this comment was disrespectful, please report it.)

 
1/30/2006 5:00:27 PMBill Wilkinson

Finally, might I comment that the part missing from this article is that all of the built-in VB6 functions mentioned at the top (Len, Mid, etc.) are *STILL* available in VB.NET. There's no particular performance advantage in using the String class methods instead of the functions [they are converted from functions to methods on String "under the covers"], so if you like the VB6-style functions, just continue to use them. (I, for one, like using LEFT and RIGHT, for example, in preference to using String.Substring.)

(If this comment was disrespectful, please report it.)

 
3/23/2006 10:50:13 AMCarlos

Excelent for Me. This code is that I was looking for.
(If this comment was disrespectful, please report it.)

 
3/28/2006 5:36:22 AMkunal

really good for beginers
(If this comment was disrespectful, please report it.)

 
5/29/2006 11:49:47 PMdurairaj

it was good,

i have one doubt,

i need to get some data from sorted list, i mean it contains some names,,

for example if it contains 50 names, in it, there are 20 names end with word "menu", i need to get take only names not with menu,
so that i can easily picked remaining 3o names, how to do it? tell me
(If this comment was disrespectful, please report it.)

 
9/12/2006 2:02:32 PMopticyclic

"...using PURE VB.NET..."
Shouldn't you be using MessageBox.Show instead of MsgBox then?
(If this comment was disrespectful, please report it.)

 
12/14/2006 3:19:13 AMSurendra

Thanks dear
(If this comment was disrespectful, please report it.)

 
1/3/2007 2:53:20 PMTake0n

Excellent!!!
It helped me million of times :)
5 from me!!!

Keep up the good work!
(If this comment was disrespectful, please report it.)

 
9/3/2007 5:14:33 AMNaresh

how can i count a specific word in a string in vb.net.(for example Textbox1.text="this is a beautiful day is", and i want to know how many time is displayed in a string")
thanx
(If this comment was disrespectful, please report it.)

 
9/30/2007 2:15:47 PMSC Project

opticyclic was right. those msgbox's should be messagebox.show

for left and right, you can use strings.left andor strings.right

dunno if thats included as part of the legacy stuff though
(If this comment was disrespectful, please report it.)

 
10/28/2007 8:52:02 PMTallion

quickly found the manipulation i was looking for. thanks!
(If this comment was disrespectful, please report it.)

 
12/29/2007 5:47:31 PM

Good Man
(If this comment was disrespectful, please report it.)

 
12/29/2007 5:51:07 PMSlam2000

good
(If this comment was disrespectful, please report it.)

 
1/21/2008 4:49:51 AMMukundaChar

Its Good
(If this comment was disrespectful, please report it.)

 
2/12/2008 11:32:34 AMWellington T. Marthas

very good !
thanks
(If this comment was disrespectful, please report it.)

 
4/10/2008 6:13:22 PMChavez Watkins

thanks for that, it'll save me the time and patience of writing my own code for these simple little functions
(If this comment was disrespectful, please report it.)

 
8/12/2008 2:29:20 PMNilesh Agrawal

very nice
(If this comment was disrespectful, please report it.)

 
10/13/2008 12:47:46 AMkshitij

Good ARticle atleast for the beginners
(If this comment was disrespectful, please report it.)

 
5/3/2010 12:10:26 PMJason Newland

Great article. Two points, IndexOf returns -1 not 0 and theres a little thing about using most functions in the string class. You have to check 1) that the start index does not exceed the length (causes an IndexOutOfRange exception or ArgumentOutOfRange) and 2) that the string passed to these functions isn't null (NullReferenceException). Also in some instances you must check that start indexs aren't -1 or you get Index/ArgumentOutRangeException. So, you really should point these out in the article if this is aimed at "noobies", as they won't know what those exceptions mean or what to do about them.
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.