Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

.NET 

[TUT] Splitting Strings [Basic]

The importance of knowing how to split strings in vb.net is so great I cannot describe it. You can use it for tons of things and it can be helpful when you're making certain programs. I am aware this is pretty basic however a lot of people ask how to do stuff like this with strings.

Code
Dim splitme As String = "I|Like|Cheese"
MsgBox(splitme.Split("|")(0).ToString)

The result of this is "I"
An array starts at 0 so we're splitting "|" and basically getting
the first result which is 0 or "I"

Code
Dim splitme As String = "I|Like|Cheese"
MsgBox(splitme.Split("|")(1).ToString)

This returns "Like" because it is the second item in the array.

Code
Dim splitme As String = "I|Like|Cheese"
MsgBox(splitme.Split("|")(2).ToString)

Finally, this returns "Cheese" because it is the third item.

If you were to try this:

Code
Dim splitme As String = "I|Like|Cheese"
MsgBox(splitme.Split("|")(3).ToString)

You get an error which states "Index was outside the bounds of the array"

The reason why is there are only 3 words and the array starts at 0
so the only results you can have are 0, 1, 2

One more quick thing people want to know how to do
is loop through a split string and display it in a messagebox.

You can do this like so:

Code
Dim splitme As String = "I|Like|Cheese"
For i = 0 To splitme.Split("|").Count - 1
MsgBox(splitme.Split("|")(i).ToString)
Next

What we are doing is a loop which says we are going to go
from 0 to the amount of words - 1.
The reason we do - 1 is because an array starts at 0 so we have
to take in account that the split count will still be the normal amount
starting from 1.

The result from the above will be 3 different message box's that say "I" "Like" "Cheese"

Hope this was helpful to the noobs out there.
If you have any other questions do not be afraid to PM me or ask away.

Thanks for the nice TUT :)
No prob! Any requests I will be happy to make more in depth tutorials.
Pretty basic, you can also do stuff like this:

Split(Input, "|")(1).Split("|")(0)
(Jun 23, 2011 10:12 PM)Cody8295 Wrote:  Pretty basic, you can also do stuff like this:

Split(Input, "|")(1).Split("|")(0)

Yup, that is another way you can do it.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[.NET] by pro_fesnoobSep 24, 2022 04:24 PM 14 797 Sep 24, 2022 04:24 PM
Last Post: BinaryFox
[.NET] by webwarlock72Jan 28, 2018 12:30 PM 14 512 Jan 28, 2018 12:30 PM
Last Post: Ninja
[C#] by RhinemannSep 15, 2017 04:14 AM 8 264 Sep 15, 2017 04:14 AM
Last Post: Rhinemann