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...
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.
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.
You may link to this article from another website, but ONLY if it is not wrapped in a frame.
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.
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
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.)
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.)
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.)
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.)
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.)
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.)
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.)
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.)
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.)
(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.)
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.)
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.)
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.)
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.)
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.)
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.)
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.)
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.)
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.)
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.)
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.)
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.)
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.)
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.)