visual studio split function issue - vb.net

I try to call split function on visual studio as below and i expect it return me 2 item in array after split, but vb return 5 results from my coding. It is consider vb issue or my coding issue?
Whole string is "NAME":"ALICE"
Dim a As String = """NAME"":""ALICE"""
Dim b() As String = a.Split(""":")
Output I expected in array after split
(1) "NAME
(2) "ALICE"

You were using this overload of String.Split(Char[]). Note that takes an array of characters. String is convertible to an array of characters (and that's why you could compile) but it is not equal. Try putting Option Strict On at the top of your code. It won't compile as you have it anymore :)
When passing a single string, each character in the string is used to split. Including each " in your argument, ":. It will split on " and :. You can get around it by passing a string array to Split using this overload of String.Split(String[], SplitStringOptions). Pass a single element array like this
Dim b = a.Split({""":"}, StringSplitOptions.RemoveEmptyEntries)
Yes, that is exactly as you said,
"NAME
"ALICE"
Do you want to get rid of the quotes in the result? You can do this
Dim b = a.Split({":", """"}, StringSplitOptions.RemoveEmptyEntries)
Then it's this,
NAME
ALICE

Dim a As String = """NAME"":""ALICE"""
Dim b() As String = a.Split(":")
this is how it evaluates

Related

How to separate data with a comma

For example, I'm having a two set of vars with data type of string:
users = "Admin, Staff"
pass = "202cb9, caf1a"
These are vars with only normal string data type. The two vars above is generated, so I could only get these kind of data. The question is:
How can I separate those data by the commas (like Admin -> 202cb9, Staff -> caf1a) and then store them into an array.
users_array(0) = "Admin"
users_array(1) = "Staff"
pass_array(0) = "202cb9"
pass_array(1) = "caf1a"
Thank you.
You can use users.Split(New Char() {","c}) as in this link.
http://www.dotnetperls.com/split-vbnet
I have two options to solve this problem:
Dim users_array() As String = users.Split(New String() {", "}, StringSplitOptions.RemoveEmptyEntries)
and:
Dim pass_array() As String = Split(users, ", ")
IMO, it is better to use ,<space> as a separator string instead of just ,, to avoid getting <space>staff at index 1.
Here the first solution works for both C# and VB.Net and second one is specific to VB.Net.
User String.Split to break strings apart on a specific character. It returns an array.

VB.Net Extract numbers from string function

My request is one that can extract a number somewhat by a search.
Example:
animalsOwned|4 would return an containing "4"
animals|3|2|1|3 would return an array containing "3", "2", "1", "3"
This would make it easier for me during a file stream reader.
Thank you
Dim astring = "ABCDE|1|2|3|4"
Dim numbers = (From s In astring
Where Char.IsDigit(s)
Select Int32.Parse(s)).ToArray()
This LINQ statement should help. It simply checks each character in a string to see if it's a digit. Note that this only applies to single digit numbers. It becomes a bit more complicated if you want "ABC123" to return 123 vs. 1, 2, 3 array.
Try regular expression. It's a powerful tool for simple text parsing.
Imports System.Text.RegularExpressions
Namespace Demo
Class Program
Shared Function Main(ByVal args As String()) As Integer
Dim array As Integer() = ExtractIntegers("animals|3|2|1|3")
For Each i In array
Console.WriteLine(i)
Next
Return 0
End Function
Shared Function ExtractIntegers(ByVal input As String) As Integer()
Dim pattern As String = "animals(\|(?<number>[0-9]+))*"
Dim match As Match = Regex.Match(input, pattern)
Dim list As New List(Of Integer)
If match.Success Then
For Each capture As Capture In match.Groups("number").Captures
list.Add(Integer.Parse(capture.Value))
Next
End If
Return list.ToArray()
End Function
End Class
End Namespace
I haven't programmed VB for awhile but I'll give you some pseudo code:
First, loop through each line of file. Call this variable Line.
Then, take the index of what you're searching for: like Line.indexOf("animalsOwned")
If it returns -1 it isn't there; continue.
Once you find it, add the Index variable to the length of the search string and 1. (Index=Index+1+Len(searchString))
Then, take a substring starting there, and end at the end of the line.
Explode the substring by | characters, then add each into an array.
Return the array.
Sorry that I can't give you much help, but I'm working on an important PHP website right now ;).
You can do a variable.Split("|") and then assign each piece to an array level.
You can do a count on string and with a while or for loop, you can assign the splited sections to array levels. Then you can do a IsNumeric() check for each array level.

splitting a string in VB

I have a ComboBox which I assign to a variable:
Dim var as String = ComboBox1.SelectedValue
Dim name As String = var.Split(",")
This gives me the error
Value of type '1-dimensional array of string' cannot be converted to String
Any ideas as to where I'm going wrong?
Split returns an array of strings. Your variable needs to be changed to an array, not just a single string.
My VB is a bit rusty, but I think you have to make name an array:
Dim name() As String = var.Split(",")
name needs to be declared as an array.
dim name() as string = var.split(",")
The split() method will break up the string based on the given character and put each newly created string into an array and return it.
This is what your error message is telling you:
Value of type '1-dimensional array of string' cannot be converted to String
The method returns an array of string, but your trying to put it into just a string!
EDIT: In response to your answer...
So far you've managed to split the string yourself with the split method. To output this to your message box, you need to concatenate the two elements in the proper order:
msgbox(name(1) & " " & name(0))
Notice I indexed the array twice! Element 1 is the first name, element 0 is the last name. Remember you got this name in lname,fname format. Passing the array itself doesn't make sense! Remember, a datatype is not equal to an array of that type, they are two different things. Therefore a string is not compatible with a string array. However, each individual element of the array is a string, and so each of those are compatible with the string type (because they're the same thing)!
Dim var As String = ComboBox1.SelectedValue
Dim temp() As String = Split(var, ",", -1, CompareMethod.Binary)
Dim name As String = temp(0)
Or maybe "name" isn't an array and the goal is to populate "name" with everything up until the first comma, in which case the fix would be:
Dim name as String = var.Split(",")(0)
Note: assumes that var is not Nothing.

Create a string and append text to it

Funny, I had a textbox and I could append strings to it.
But now I create a string like this:
Dim str As String = New String("")
And I want to append to it other strings. But there is no function for doing so. What am I doing wrong?
Concatenate with & operator
Dim str as String 'no need to create a string instance
str = "Hello " & "World"
You can concate with the + operator as well but you can get yourself into trouble when trying to concatenate numbers.
Concatenate with String.Concat()
str = String.Concat("Hello ", "World")
Useful when concatenating array of strings
StringBuilder.Append()
When concatenating large amounts of strings use StringBuilder, it will result in much better performance.
Dim sb as new System.Text.StringBuilder()
str = sb.Append("Hello").Append(" ").Append("World").ToString()
Strings in .NET are immutable, resulting in a new String object being instantiated for every concatenation as well a garbage collection thereof.
Another way to do this is to add the new characters to the string as follows:
Dim str As String
str = ""
To append text to your string this way:
str = str & "and this is more text"
Use the string concatenation operator:
Dim str As String = New String("") & "some other string"
Strings in .NET are immutable and thus there exist no concept of appending strings. All string modifications causes a new string to be created and returned.
This obviously cause a terrible performance. In common everyday code this isn't an issue, but if you're doing intensive string operations in which time is of the essence then you will benefit from looking into the StringBuilder class. It allow you to queue appends. Once you're done appending you can ask it to actually perform all the queued operations.
See "How to: Concatenate Multiple Strings" for more information on both methods.

How to split in VB.NET

I am using VB.NET code.
I have got the below string.
http://localhost:3282/ISS/Training/SearchTrainerData.aspx
Now I want to split the above string with "/" as well. I want to store the value SearchTrainerData.aspx in a variable.
In my case
Dim str as String
str = "SearchTrainerData.aspx"
What would be the code which will split the above string and further store it in a variable?
Try to use the function String.Split.
Your "string" is obviously a URL which means you should use the System.Uri class.
Dim url As Uri = New Uri("http://localhost:3282/ISS/Training/SearchTrainerData.aspx")
Dim segments As String() = url.Segments
Dim str As String = segments(segments.Length - 1)
This will also allow you to get all kinds of other interesting information about your "string" without resorting to manual (and error-prone) parsing.
The Split function takes characters, which VB.NET represents by appending a 'c' to the end of a one-character string:
Dim sentence = "http://localhost:3282/ISS/Training/SearchTrainerData.aspx"
Dim words = sentence.Split("/"c)
Dim lastWord = words(words.length - 1)
I guess what you are actually looking for is the System.Uri Class. Which makes all string splitting that you are looking for obsolete.
MSDN Documentation for System.Uri
Uri url = new Uri ("http://...");
String[] parts = url.Segments;
Use split(). You call it on the string instance, passing in a char array of the delimiters, and it returns to you an array of strings. Grab the last element to get your "SearchTrainerData.aspx."