Quick Search for:  in language:    
ALL,PURE,VBNET,string,manipulation,example,VB
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
.Net Stats

 Code: 140,189. lines
 Jobs: 425. postings

 How to support the site

 
Sponsored by:

 
You are in:
 

Does your code think in ink?
Login





Latest Code Ticker for .Net.
Click here to see a screenshot of this code!C# to VB.NET Converter
By MAJED_SINJAB on 12/30

(Screen Shot)

Click here to see a screenshot of this code!DX9 Ortho Projection
By Created by: X on 12/30

(Screen Shot)

FileCopier
By Mähr Stefan on 12/30


Click here to see a screenshot of this code!GnuCli
By Mähr Stefan on 12/30

(Screen Shot)

GSP
By Mähr Stefan on 12/30


A__Start and End a Process__A
By Yuri Vishnevsky on 12/29


Web Custom Control (Credit Card)
By Tahir Naveed on 12/29


ScreenCapture
By SpaceMonkey on 12/27


Credit Card Verification XML Web Service
By Tahir Naveed on 12/27


Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!

Affiliate Sites



 
 
   

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

Print
Email
 

Submitted on: 3/25/2002 9:21:32 AM
By: tHe_cLeanER  
Level: Beginner
User Rating: By 35 Users
Compatibility:VB.NET

Users have accessed this article 37718 times.
 
(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 15 submission(s) by this author

 

 
Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Reason:
 
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 AM:Omer
I thought you made these functions yourself :s
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/26/2002 2:29:56 AM:Mohammad Omer Sadiq
i thought you made these functions yourself in .NET
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/26/2002 4:19:51 AM:tHe_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
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/26/2002 10:15:58 AM:roswellevent
Good Job!
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
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 :)
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
4/18/2002 11:48:03 AM:hi,
how about the left(xxx,3) or right(xxx,5) funcytion in vb.net
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
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 :)
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
4/18/2002 2:38:55 PM:Thraka
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)
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
4/23/2002 9:56:44 AM:tHe_cLeanER
thanks for the feedback thraka, certainly for advanced users that will be usefull, but this tutorial was intended for beginners :)
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
5/19/2002 5:40:48 PM:Noodlez
...how the hell do you use Left() and Right()
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/19/2002 2:51:47 AM:wEnGwAsHeRe
thanks for the info
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/20/2002 12:41:06 PM:Lewis Moten
Interesting. VB.Net is moulding itself simular to javascript. This could prove to be confusing at first.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
8/13/2002 9:56:38 AM:Bjarni
Where is IsNull ??
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
8/13/2002 9:56:51 AM:Bjarni
Where is IsNull() ??
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
9/5/2002 5:44:47 AM:
Great Job Cleaner
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
1/3/2003 1:43:15 AM:UDMX IOCP©
good job... saved me sometime... lolz 5 globes.. just started learnin..
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
1/3/2003 1:44:03 AM:UDMX IOCP©
btw.. this page's textcolor is orange...lolz
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
1/3/2003 2:41:08 AM:tHe_cLeanER
lol yeh, the orange is because of the CSS file i used :D
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
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.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
1/22/2003 1:34:58 PM:tHe_cLeanER
code updated, thanks [blank]
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/20/2003 11:43:28 PM:
do you know of a replacement for the vb string$ function.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
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.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
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
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/17/2003 1:56:23 PM:Dan Fogelberg
LEFT example s = Left(
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/17/2003 2:45:47 PM:Dan Fogelberg
<PRE>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"
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
6/19/2003 7:20:11 AM:My Address
Good help for me!
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
11/16/2003 9:55:13 PM:
Nice, Very nice indeed.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | .Net Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.