I am using the following code to split a string and retrieve them:
Private Sub Button1_Click(sender As Object, e As EventArgs)
Handles Button1.Click
Dim s As String = "a,bc,def,ghij,klmno"
Dim parts As String() = s.Split(New Char() {","c})
Dim part As String
For Each part In parts
MsgBox(part(0))
Next
End Sub
But the message box shows only the first character in each splitted string (a,b,d,g,k).
I want to show only the first word, what am I doing wrong?
It is not clear from your question, but if you want only the first word in your array of strings then no need to loop over it
Dim firstWord = parts(0)
Console.WriteLine(firstWord) ' Should print `a` from your text sample
' or simply
Console.WriteLine(parts(0))
' and the second word is
Console.WriteLine(parts(1)) ' prints `bc`
You already have each part - just display it:
For Each part In parts
MsgBox(part)
Next
part(0) will return the first item in the character collection that is a string.
If you want a specific index into the returned string array (as suggested by your comment), just access it directly:
Dim parts As String() = s.Split(New Char() {","c})
Dim firstPart As String = parts(0)
Dim thirdPart As String = parts(2)
You need to show part not part(0)
For Each part In parts
MsgBox(part)
Next
Related
I would like to ask for your help regarding my problem. I want to create a module for my program where it would read .txt file, find a specific value and insert it to the text box.
As an example I have a text file called system.txt which contains single line text. The text is something like this:
[Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]
What i want to do is to get only the last name value "xxx_xxx" which every time can be different and insert it to my form's text box
Im totally new in programming, was looking for the other examples but couldnt find anything what would fit exactly to my situation.
Here is what i could write so far but i dont have any idea if there is any logic in my code:
Dim field As New List(Of String)
Private Sub readcrnFile()
For Each line In File.ReadAllLines(C:\test\test_1\db\update\network\system.txt)
For i = 1 To 3
If line.Contains("Last Name=" & i) Then
field.Add(line.Substring(line.IndexOf("=") + 2))
End If
Next
Next
End Sub
Im
You can get this down to a function with a single line of code:
Private Function readcrnFile(fileName As String) As IEnumerable(Of String)
Return File.ReadLines(fileName).Where(Function(line) RegEx.IsMatch(line, "[[[]Last Name=(?<LastName>[^]]+)]").Select(Function(line) RegEx.Match(line, exp).Groups("LastName").Value)
End Function
But for readability/maintainability and to avoid repeating the expression evaluation on each line I'd spread it out a bit:
Private Function readcrnFile(fileName As String) As IEnumerable(Of String)
Dim exp As New RegEx("[[[]Last Name=(?<LastName>[^]]+)]")
Return File.ReadLines(fileName).
Select(Function(line) exp.Match(line)).
Where(Function(m) m.Success).
Select(Function(m) m.Groups("LastName").Value)
End Function
See a simple example of the expression here:
https://dotnetfiddle.net/gJf3su
Dim strval As String = " [Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]"
Dim strline() As String = strval.Split(New String() {"[", "]"}, StringSplitOptions.RemoveEmptyEntries) _
.Where(Function(s) Not String.IsNullOrWhiteSpace(s)) _
.ToArray()
Dim lastnameArray() = strline(1).Split("=")
Dim lastname = lastnameArray(1).ToString()
Using your sample data...
I read the file and trim off the first and last bracket symbol. The small c following the the 2 strings tell the compiler that this is a Char. The braces enclosed an array of Char which is what the Trim method expects.
Next we split the file text into an array of strings with the .Split method. We need to use the overload that accepts a String. Although the docs show Split(String, StringSplitOptions), I could only get it to work with a string array with a single element. Split(String(), StringSplitOptions)
Then I looped through the string array called splits, checking for and element that starts with "Last Name=". As soon as we find it we return a substring that starts at position 10 (starts at zero).
If no match is found, an empty string is returned.
Private Function readcrnFile() As String
Dim LineInput = File.ReadAllText("system.txt").Trim({"["c, "]"c})
Dim splits = LineInput.Split({"]["}, StringSplitOptions.None)
For Each s In splits
If s.StartsWith("Last Name=") Then
Return s.Substring(10)
End If
Next
Return ""
End Function
Usage...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = readcrnFile()
End Sub
You can easily split that line in an array of strings using as separators the [ and ] brackets and removing any empty string from the result.
Dim input As String = "[Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]"
Dim parts = input.Split(New Char() {"["c, "]"c}, StringSplitOptions.RemoveEmptyEntries)
At this point you have an array of strings and you can loop over it to find the entry that starts with the last name key, when you find it you can split at the = character and get the second element of the array
For Each p As String In parts
If p.StartsWith("Last Name") Then
Dim data = p.Split("="c)
field.Add(data(1))
Exit For
End If
Next
Of course, if you are sure that the second entry in each line is the Last Name entry then you can remove the loop and go directly for the entry
Dim data = parts(1).Split("="c)
A more sophisticated way to remove the for each loop with a single line is using some of the IEnumerable extensions available in the Linq namespace.
So, for example, the loop above could be replaced with
field.Add((parts.FirstOrDefault(Function(x) x.StartsWith("Last Name"))).Split("="c)(1))
As you can see, it is a lot more obscure and probably not a good way to do it anyway because there is no check on the eventuality that if the Last Name key is missing in the input string
You should first know the difference between ReadAllLines() and ReadLines().
Then, here's an example using only two simple string manipulation functions, String.IndexOf() and String.Substring():
Sub Main(args As String())
Dim entryMarker As String = "[Last Name="
Dim closingMarker As String = "]"
Dim FileName As String = "C:\test\test_1\db\update\network\system.txt"
Dim value As String = readcrnFile(entryMarker, closingMarker, FileName)
If Not IsNothing(value) Then
Console.WriteLine("value = " & value)
Else
Console.WriteLine("Entry not found")
End If
Console.Write("Press Enter to Quit...")
Console.ReadKey()
End Sub
Private Function readcrnFile(ByVal entry As String, ByVal closingMarker As String, ByVal fileName As String) As String
Dim entryIndex As Integer
Dim closingIndex As Integer
For Each line In File.ReadLines(fileName)
entryIndex = line.IndexOf(entry) ' see if the marker is in our line
If entryIndex <> -1 Then
closingIndex = line.IndexOf(closingMarker, entryIndex + entry.Length) ' find first "]" AFTER our entry marker
If closingIndex <> -1 Then
' calculate the starting position and length of the value after the entry marker
Dim startAt As Integer = entryIndex + entry.Length
Dim length As Integer = closingIndex - startAt
Return line.Substring(startAt, length)
End If
End If
Next
Return Nothing
End Function
I need to extract text from a text file starting with the order number(eg. Order1) and ending with an empty line with all other lines between the order number and the empty line extracted as well for a query. Really have no idea how to go about this so any help is greatly appreciated!
so the file name is "CustomerDetails.txt" and I'd imagine the code would look something like this
If IO.File.Exists("CustomerDetails.txt") Then
Dim inFile As IO.StreamReader = IO.File.OpenText(“CustomerDetails.txt")
End If
and then taking for example "order1" in that text file until the blank space and displaying that is a list box
"Really have no idea how to go about this "
The thinking could go like this...
A text file has a string in it.
I could look up the String class in .net and see if there are any methods that could help me.
Search for "String class in .net"
Looks like we can use a combination of String.IndexOf(String, Int32) and String.Substring(Int32, Int32)
Find the IndexOf your order. The string will be the order "Order1" and we will start looking at index 0 so the Int32 will be 0. Then find the end index. Start looking at the index we just found and stop at the first blank line. We can get the length required by the `.Substring method by subtracting the start index from the end index. Now we can extract the text of Order 1 with the substring method.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim OrderText As String = "Order 1" 'this could be set with TextBox1.Text
'Get the string out of the file
Dim s As String = File.ReadAllText("CustomerDetails.txt")
'Find the index of the order, this overload assumes start index is 0
Dim startIndex As Integer = s.IndexOf(OrderText) 'starts lookint at beginning
'Find the index of the first blank line after the startIndex
'2 new lines make a bland line
Dim endIndex As Integer = s.IndexOf(Environment.NewLine & Environment.NewLine, startIndex)
'Return the string that stars at startIndex with a length of end minus start
Dim Order As String = s.Substring(startIndex, endIndex - startIndex)
'I am going to guess that the details of the order are on separate lines
Dim lines() As String = Order.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
For Each line As String In lines
ListBox1.Items.Add(line)
Next
End Sub
I am trying to retrive the value of the text between the first and second backslashes... but my coding skills have brought me this far and no futher.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim TEST As String = "ONE\TWO\TRHREE\FOR\FIVE"
Dim splitted = TEST.Split("\"c)
Dim values = splitted.Skip(1).Take(splitted.Length - 2).ToArray()
MsgBox(values)
End Sub
Use regular expressions
Dim TEST as String = "ONE\TWO\TRHREE\FOR\FIVE"
Dim matches As MatchCollection = Regex.Matches(TEST, "\\(.|\n)*?\\", RegexOptions.IgnoreCase)
Now if you want those values to come out in message boxes
For Each ma As Match In matches
MsgBox(ma.ToString.Trim({"\"c}))
Next
This will get you both "TWO" and "FOR". If you want just "TWO" then matches(0) is all you need.
Alternatively, if you just want to get the matches into an array in one line, then have each value of the array in a single message box:
Dim values = Regex.Matches(TEST, "\\(.|\n)*?\\").Cast(Of Match)().[Select](Function(m) m.Value).ToArray()
MsgBox(String.Join(", ", values))
Use the Split function. It will split on a string and store the separated values in an array. This is the easiest of all the answers here and is probably the most correct way of doing this.
This is the VB way of doing it:
Dim s() As String = Split("ONE\TWO\TRHREE\FOR\FIVE", "\")
MessageBox.Show(s(1))
And this is the .NET way of doing it:
Dim mainString As String = "ONE\TWO\TRHREE\FOR\FIVE"
Dim s() As String = mainString.Split("\")
MessageBox.Show(s(1))
If you want "Two" as result, this should be the simplest approach:
Dim allToken As String() = "ONE\TWO\TRHREE\FOR\FIVE".Split("\"c)
Dim relevantPart = allToken.Skip(1).Take(1)
Dim result As String = String.Concat(relevantPart) ' "Two"
If you don't want a single string but a String() use ToArray:
Dim result As String() = relevantPart.ToArray()
Side-Note: you can't output an array directly, you could use String.Join:
MsgBox(String.Join(", ", result)) ' f.e. comma separated
Based on the code I provided I would like to explode a string into two. The code is working but only if SearchQuery contains two phrases.
Private Sub SearchTxt_PreviewKeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles SearchTxt.PreviewKeyDown
Dim SearchQuery As String = SearchTxt.Text
Dim MyString As System.String
MyString = SearchQuery
Dim OutPutArray() As System.String
OutPutArray = Split(MyString, " ", -1)
''MsgBox(OutPutArray(0)) - Working
MsgBox(OutPutArray(1)) ' error - Index was outside the bounds of the array.
end sub
An array is always zero based (every type of collection is), so OutPutArray(1) tries to access the second item not the first. If it contains only one you get the exception.
Instead you want: OutPutArray(0)
If you don't know if it contains two, check it:
Dim first As String = OutPutArray(0)
Dim second As String = Nothing
If OutPutArray.Length > 1 Then
second = OutPutArray(1)
End If
As an aside, i recommend to use .NET methods, so String.Split:
Dim OutPutArray As String() = MyString.Split() ' splits by white-spaces, tabs or newlines
or, if you only want to split by spaces:
Dim OutPutArray As String() = MyString.Split({" "}, StringSplitOptions.None)
Simple beginner exercise:
There's an input box where you put in your name seperated by spaces, then get the first letter from the first and last name and out put it to a label
I.e (Joe Bob) = JB
I know this could be done with an array, but the exercise is more to using string functions like substring, IndexOf, Remove, Replace etc...
There is the handy string method Split which splits a string at whitespaces by default, if you don't specify another delimiter.
Dim words As String() = TextBox1.Text.Split()
Dim initials As String = ""
For Each word As String In words
initials &= word(0)
Next
Note: Strings can be indexed as if they were Char arrays. word(0) is the first character of word.
initials &= word(0)
is shorthand for
initials = initials & word(0)
You can try this:
dim str as String=TextBox1.Text
Label1.Text=str.Remove(1, str.LastIndexOf(" ")).Remove(2)
If you want, you can do it in one line:
Label1.Text = TextBox1.Text.Remove(1, TextBox1.Text.LastIndexOf(" ")).Remove(2)
Could try something like this too!
Dim str As String = textBox1.Text
Dim initials As String = New String(str.Split(" "c).Select(Function(f) f(0)).ToArray)
You can try using the SubString and Split Methods.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim myInitials As String
Dim myName As String = "Joe Bob"
myInitials = myName.Substring(0, 1) & myName.Split(" ")(1).Substring(0, 1)
End Sub