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
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 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)
I have in a text file lines of this format:
word1|word2|word3
anotherword1|anotherword2
I'm trying to split each word one by one per every line of that file and once program detect if the richtextbox has one of these words will replace that word with the unsplitted line. Example: From word1 to word1|word2|word3
Here is what I have so far:
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
For Each line As String In File.ReadLines("C:\text.txt")
Dim input As String = line
Dim result As String() = line.Split(New String() {"|"}, StringSplitOptions.None)
For Each s As String In result
Try
Dim linex As String = line
RichTextBox1.Text = RichTextBox1.Text.Replace(s, " " & linex)
Catch exxx As Exception
End Try
Next
Next
End Sub
It works great, but after the replacement, the replaced text still have the detected word and it keep replacing itself with word1|word2|word3 forever. And I want do do the process just once.
Like this: Click to see
Due to the format the words are stored in, it will be much easier to achieve what you want using Regular Expressions:
Dim lines = File.ReadLines("C:\text.txt")
For Each line As String In lines
Dim pat = String.Format("\b({0})\b", line)
RichTextBox1.Text = Regex.Replace(RichTextBox1.Text, pat, line)
Next
This should do pretty much what you want.
Check it here.
I am trying to figure out how to get a message box to show only specific words from a text file, which contains all of the words within the dictionary. I have tried various different ways, but cannot get it to work, but I do think I am on the right track so just need some pointers.
Basically, there is a scrambled up string, which is different every time, and is contained within a label. I want the program to only show words which contains the letters inside the scrambled string, but not sure how to achieve this?
Here is the code that I have so far:
Private Sub btnAnswers_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAnswers.Click
Dim hash As List(Of String) = New List(Of String)(System.IO.File.ReadAllLines("C:\Users\Katie\Documents\Project\dictionary.txt"))
Dim Letters As String
Dim OneCharacter As String
Dim Found As Boolean
Dim item As String
Dim AllCharacters As String
Found = False
Letters = lblLetters.Text
For i = 0 To Letters.Length - 1
OneCharacter = Letters.Substring(i, 1)
For Each item In hash
If item.Contains(OneCharacter) Then
Found = True
AllCharacters = OneCharacter
Else
Found = False
End If
MsgBox(item)
Next
Next i
End Sub
The message box does show up words, from the dictionary, but words can contain letters that are not present in the label string, so my code is wrong. Can anyone help? Apologies, but I am new to programming.
With a simple modification to the previous answer you can restrict the output to only words that contain only the scrambled letters:
Private Sub btnAnswers_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim hash As List(Of String) = New List(Of String)(System.IO.File.ReadAllLines("C:\Users\Katie\Documents\Project\dictionary.txt"))
Dim Letters As String = lblLetters.Text
For Each item As String In hash
Dim word As String = item.ToLower()
For i = 0 To Letters.Length - 1
Dim OneCharacter As Char = Char.ToLower(Letters(i))
While word.Contains(OneCharacter)
word = word.Remove(word.IndexOf(OneCharacter), 1)
End While
Next
If (word.Length = 0) Then
'The given dictionary entry includes all the letters in the label. No more iterations will be performed
MsgBox(item)
Exit For
End If
Next
End Sub
With this code if the scrambled letters contain 'bok' then "book" will get selected. However removing the while loop and leaving only the remove statement, will ensure that only the exact number of each different letter will match. so that 'obok' will be needed to match "book".
As suggested by Steven Doggart, you have to invert the loop nesting. What you want is going through all the dictionary entries and, for each of them, checking if it contains all the letters in the string. Your loop structure is not allowing to do that.
I have performed the required updates in your code. Bear in mind that this code ignores caps ("A" is the same than "a").
Private Sub btnAnswers_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim hash As List(Of String) = New List(Of String)(System.IO.File.ReadAllLines("C:\Users\Katie\Documents\Project\dictionary.txt"))
Dim Letters As String = lblLetters.Text
For Each item As String In hash
Dim Found As Boolean = True
For i = 0 To Letters.Length - 1
Dim OneCharacter As String = Letters.Substring(i, 1)
Dim itemToLower As String = item.ToLower()
If Not itemToLower.Contains(OneCharacter.ToLower()) Then
Found = False
Exit For
End If
Next i
If (Found) Then
'The given dictionary entry includes all the letters in the label. No more iterations will be performed
MsgBox(item)
Exit For
End If
Next
End Sub
This code looks for keys containing all the characters in the given label (not at the contrary), that is: with a label "dict", "dictentry" would be right.
In any case, the whole point of my answer is not delivering a code which you just have to execute; the point of this code is helping you to understand what you did wrong and how to start doing things right. If you are not interested in this exact functionality, you woud have to edit my code such that what you want can be accomplished; or, ideally, you would be writing your own code completely from scratch.
You're calling MsgBox(item) outside of the if statement that determines whether the current word contains the current character. Which means it's going to pop up for every letter, every word. Move MsgBox(item) inside the first half of the if statement if you only want it to show when the letter is actually found in the word.
I'd also suggest following Steven Doggart's advice and reversing the way the loops are nested. If the characters are the outer loop, you could get the message box multiple times per word (e.g., if your letters are "sdf" and one of the words is "foods," it will pop up 3 times).
For Each item In hash
For i = 0 To Letters.Length - 1
OneCharacter = Letters.Substring(i, 1)
If item.Contains(OneCharacter) Then
Found = True
AllCharacters = OneCharacter
MsgBox(item)
Else
Found = False
End If
Next
Next
VB 2010 - Beginner here,
I am creating a hangman game for a assignment and I am having trouble replacing the text of a string with dashes. I am not sure if I need to convert the string to a charArray() or if I can use the string.Replace function. i know i need to loop it unsure how..
terribly confused i need some help. As I am learning please try and keep it simple with reason please.
My sandbox code so far:
Imports System.IO
Public Class Form1
Private Const TEST = "test.txt"
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim WordString As String = Nothing
Dim NewWordInteger As Integer
Dim RandomWord As New Random(System.DateTime.Now.Millisecond) 'Load a new word at the time it was initiated
'Load words from test file into the array
Dim WordArray() As String = File.ReadAllLines(TEST) 'Reads words from list and declares each as a string
'Select Random word from the number of words in the dictionary.txt file
NewWordInteger = RandomWord.Next(0, 4)
'Display RandomWord in textbox as STRING..
WordString = WordArray(NewWordInteger) ' Assigns wordstring a word from the arrany & random by the NewWordInterger Substring..
WordDisplayTextBox.Text = WordString ' will display the word in the textbox
SolveLabel.Text = WordString ' will display the word in the Solve label
'Will shoe the array word and the word/string position in the TEST.file
ListBox1.Items.Add(WordString) ' will show the word
ListBox2.Items.Add(NewWordInteger) ' will show the string position in the TEST.file
'search string and replace letters with _ (Dashes)
Dim charArray() As Char = WordDisplayTextBox.Text.ToCharArray
For Each item As Char In WordDisplayTextBox.Text
WordDisplayTextBox.Text = WordString.Replace(item, "_")
Next
End Sub
End Class
If you want to replace all the characters of a string with dashes, why not just make a new string that consists only of dashes, that is the same length as the starting string? Isn't that the same thing?
WordDisplayTextBox.Text = New String("_", WordString.Length)
Loop through the length of the WordString and each time write "__" inside the WordDisplayTextBox
For i As Integer = 1 To Len(txtWordString.Text)
WordDisplayTextBox.Text += "__" + " " 'Space separates the dashes for clarity
Next