VB.NET Index Of, finding word position - vb.net

I have a basic piece of code.
Sub Main()
Dim Test As String = "test example"
Console.WriteLine(Test.IndexOf("example"))
Console.ReadLine()
End Sub
The output would be "5" as the position of the start of the specified string is 5. I would still like to use indexof but how can i make it find the word location of the specified string such as it would output "2" as the word location is the 2nd word.

Use Array.IndexOf method
Dim str As [String] = "First Second Third Forth"
Dim arr As String() = str.Split(" "C)
Console.WriteLine(Array.IndexOf(arr, "Second") + 1)

Related

Get a specific value from the line in brackets (Visual Studio 2019)

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

position of words in VB.net

I am trying to make a program that shows a keyword's position(s) in a string
my program :
Sub Button1Click(sender As Object, e As EventArgs)
Dim text1 As String = textBox1.Text
Dim keyword As String = textBox2.Text
Dim Array1() As String = text1.Split(" ")
For Each item In Array1
If item = keyword Then
For c = 1 To Array1.Length
Dim input As String
input = c
listbox1.Items.Add("your word appears in the positions" & input)
Next
End If
Next
End Sub
But it does not display the position of that specific word but just the position of every word. Any1 help?
Using the method provided by the .Net framework called .IndexOf("<yourWord>"), you can find the position of a word in VB.Net. If a word exists more than once in a string, use a loop which searches for the word, returns the position of it to an array, then cuts the string to that position and starts over again. At the end, you get an array with all positions of the word you were searching for.
Try this.... it should give you some ideas....
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim Pattern As String = "The"
Dim Test As String = "The quick brown fox jumps over the lazy dog"
For Each m As Match In Regex.Matches(Test, Pattern, RegexOptions.IgnoreCase)
Console.WriteLine(String.Format("'{0}' :: occurs at position {1}", m.Value, m.Index))
Next
End Sub
End Module

How to find indexes for certain character in a string VB.NET

I'm beginner with VB.net.
How do I read indexes for certain character in a string? I read an barcode and I get string like this one:
3XXX123456-C-AA123456TY-667
From that code I should read indexes for character "-" so I can cut the string in parts later in the code.
For example code above:
3456-C
6TY-667
The length of the string can change (+/- 3 characters). Also the places and count of the hyphens may vary.
So, I'm looking for code which gives me count and position of the hyphens.
Thanks in advance!
Use the String.Splt method.
'a test string
Dim BCstring As String = "3XXX123456-C-AA123456TY-667"
'split the string, removing the hyphens
Dim BCflds() As String = BCstring.Split({"-"c}, StringSplitOptions.None)
'number of hyphens in the string
Dim hyphCT As Integer = BCflds.Length - 1
'look in the debuggers immediate window
Debug.WriteLine(BCstring)
'show each field
For Each s As String In BCflds
Debug.WriteLine(String.Format("{0,5} {1}", s.Length, s))
Next
'or
Debug.WriteLine(BCstring)
For idx As Integer = 0 To hyphCT
Debug.WriteLine(String.Format("{0,5} {1}", BCflds(idx).Length, BCflds(idx)))
Next
If all you need are the parts between hyphens then as suggested by dbasnett use the split method for strings. If by chance you need to know the index positions of the hyphens you can use the first example using Lambda to get the positions which in turn the count give you how many hyphens were located in the string.
When first starting out with .NET it's a good idea to explore the various classes for strings and numerics as there are so many things that some might not expect to find that makes coding easier.
Dim barCode As String = "3XXX123456-C-AA123456TY-667"
Dim items = barCode _
.Select(Function(c, i) New With {.Character = c, .Index = i}) _
.Where(Function(item) item.Character = "-"c) _
.ToList
Dim hyphenCount As Integer = items.Count
Console.WriteLine("hyphen count is {0}", hyphenCount)
Console.WriteLine("Indices")
For Each item In items
Console.WriteLine(" {0}", item.Index)
Next
Console.WriteLine()
Console.WriteLine("Using split")
Dim barCodeParts As String() = barCode.Split("-"c)
For Each code As String In barCodeParts
Console.WriteLine(code)
Next
Here is an example that'll split your string and allow you to parse through the values.
Private Sub TestSplits2Button_Click(sender As Object, e As EventArgs) Handles TestSplits2Button.Click
Try
Dim testString As String = "3XXX123456-C-AA123456TY-667"
Dim vals() As String = testString.Split(Convert.ToChar("-"))
Dim numberOfValues As Integer = vals.GetUpperBound(0)
For Each testVal As String In vals
Debug.Print(testVal)
Next
Catch ex As Exception
MessageBox.Show(String.Concat("An error occurred: ", ex.Message))
End Try
End Sub

Find position of a word in a string

I have to implement a search in following method,
Let :
Dim checkin As String = "This is the base string, i have to find a word here"
Dim valueSearch As String="to find a word"
Now the algorithm to be implemented is:
Dim str() As String = Split(checkin , " ")
Dim Position As Integer
Position=Find Position of str(0) in the string
Check str(1) with the next word after positionth word in checkin
if not equal continue the second step with str(1)
if Dim valueSearch As String="to find a game" then
i have to display a message that "to find a" is present
My question is that is it possible to find the position of a word in a string using
string.Contains() operation. or any other possibility to implement this algorithm?
Try Like this
Create recursive Method. Use String.Contains. Its true then return else continue the method.
private Sub Recursive(ByVal xStr As String, ByVal xSearch As String)
If xStr.Contains(xSearch) Then
MsgBox(xSearch)
ElseIf xSearch.Contains(" ") Then
Recursive(xStr, xSearch.Substring(0, xSearch.LastIndexOf(" ")))
Else
MsgBox("Not Founded")
End If
End Sub
Call Recursive("This is the base string, i have to find a word here",
"to find a game")
String.Contains(), INSTR or IndexOf should all do what you want
http://msdn.microsoft.com/en-us/library/dy85x1sa(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/8460tsh1(v=vs.90).aspx
http://msdn.microsoft.com/en-us/library/2y7ddk24.aspx

Simple get initials from string - Visual Basic

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