VB.NET For Each New Line - vb.net

I need help making a function that opens a file and for each new line, make a variable like explode("\n", $var) in PHP. I tried
Dim words As String = GetFileContents(OpenFileDialog1.FileName)
For Each word As String In words
Dim doHash As String = MD5(word)
If String.Equals(doHash, hash.Text) Then
Label2.Text = "derp"
Else
Label2.Text = "lol"
End If
Next
but it makes each letter a new variable.

You want to use System.IO.File.ReadLines(OpenFileDialog1.FileName). That will cause the For Each loop to get each line separately.
Specifically:
For Each word As String In File.ReadLines(OpenFileDialog1.FileName)
Dim doHash As String = MD5(word)
If String.Equals(doHash, hash.Text) Then
Label2.Text = "derp"
Else
Label2.Text = "lol"
End If
Next
I notice that your php example is definitely splitting on newlines, but your loop variable is called word. Does your file have one word per line? Doesn't matter much, but I wanted to double check that you're okay with the loop getting each line, not each word (if there's more than one word per line).

Related

When I run the code, get the results and repeat, the previous user input displays right before the new user input. Any idea?

Can anyone help steer me into the right direction?
I am trying to separate the string into characters. If the character is lowercase then the program will uppercase it and vice versa.
Module Module1
Sub Main()
Dim Input As String
Dim Output As New Text.StringBuilder()
Dim repeat As String = "Y"
Do While repeat = "Y"
Console.Clear()
Console.WriteLine("Please enter a word or" &
"phrase and I will change upper case to lower case and vice versa")
Input = Console.ReadLine
For Each ch As Char In Input
If Char.IsLower(ch) Then
Output.Append(Char.ToUpper(ch))
ElseIf Char.IsUpper(ch) Then
Output.Append(Char.ToLower(ch))
Else
Output.Append(ch)
End If
Next
Console.WriteLine(Output.ToString())
Console.Write("Lets try another (Y/N) ")
repeat = UCase(Console.ReadLine())
Loop
Console.ReadKey()
End Sub
End Module
Think about what you're doing with Output; you keep appending to it, but never remove the results from the previous loop from it, so it's gonna display it again and again.
So to fix your problem you need to make sure output is emptied before adding new characters to it. I don't really work with stringbuilders but a simple way would be to just do
Output = New Text.StringBuilder()
at the beginning of your loop

How to find and delete matching words in two different text files in VB?

Its a wordy question, but basically I want to have VB check textfile1 for matching words in textfile2, and then delete all instances of similar words in textfile2 and output the results as results.txt.
Outputting results shouldn't be too difficult, but i'm unsure on where to proceed when it comes to recognizing similar wordage. Also, would it be possible to set up a whitelist (there's going to be one word repeated over and over - which I don't want deleted).
This is my open file / read file dialogue which I use for both prompts, and both are displayed visually in a textbox.
Sub Maplist()
If txtFile.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Dim sr As New System.IO.StreamReader(txtFile.FileName)
tbx1.Text = sr.ReadToEnd
sr.Close()
End If
Thanks for any help!
Edit:
A sample of the first text file looks like this:
map_01, 200/250
map_03, 358/450
map_06, 528/2000
The second file looks like:
map_01
map_02
map_03
map_04
map_05
map_06
Basically the second file is the "master list'. I want the program to recognize a matching word between both files (for instance, the 01 in map_01) and then delete the entry from the master list. When I was talking about whitelisting I was concerned that it would match a word like"map" and delete everything in the master list. I didn't wanted it to delete the whole word just because it matched "map"
You have to make an array of words from both the TextFile and compare those. I did it for you here:
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
'make array of words from both the files
Dim text1Array() As String = TextBox1.Text.Split(" ")
Dim text2Array() As String = TextBox2.Text.Split(" ")
Dim NewText As String
NewText = TextBox2.Text
'loop through all the words in first array
For i = 0 To text1Array.Length - 1
'loop through all the words in second array
For j = 0 To text2Array.Length - 1
'match the words
If text1Array(i) = text2Array(j) Then
'replace the found word with an empty character
NewText = NewText.Replace(text2Array(j), String.Empty)
'delete double space
NewText = NewText.Replace(" ", " ")
End If
Next
Next
'save it into third textbox
TextBox3.Text = NewText
End Sub
I checked it like this:
Textbox1 contained :
one two three four five six seven eight nine ten eleven twelve
TextBox2 contained :
one subaz three sarma five loves six coding eight ten all the twelve time
After clicking the button, TextBox3 contained:
subaz sarma loves coding all the time
This works perfectly fine.
Now, about the whitelist, let's say you don't want to remove "five" even if it's matched. Do this:
Dim WhiteListWord As String = "five"
And change the condition as :
If text1Array(i) = text2Array(j) And text1Array(i) <> WhiteListWord Then
New output in the textbox3 will be :
subaz sarma five loves coding all the time

How can i check for a character after certain text within a listbox?

How can i check for a character after other text within a listbox?
e.g
Listbox contents:
Key1: V
Key2: F
Key3: S
Key4: H
How do I find what comes after Key1-4:?
Key1-4 will always be the same however what comes after that will be user defined.
I figured out how to save checkboxes as theres only 2 values to choose from, although user defined textboxes is what im struggling with. (I have searched for solutions but none seemed to work for me)
Usage:
Form1_Load
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
Which textbox1.text would then contain V / whatever the user defined.
I did try something that kind of worked:
Form1_Load
Dim UsersKey as string = "V"
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
but i'm not sure how to add additional letters / numbers to "V", then output that specific number/letter to the textbox. (I have special characters blocked)
Reasoning I need this is because I have created a custom save settings which saves on exit and loads with form1 as the built in save settings doesn't have much customization.
e.g Can't choose save path, when filename is changed a new user.config is generated along with old settings lost.
Look at regular expressions for this.
Using the keys from your sample:
Dim keys As String = "VFSH"
Dim exp As New RegEx("Key[1-4]: ([" & keys& "])")
For Each item As String in ListBox1.Items
Dim result = exp.Match(item)
If result.Success Then
TextBox1.Text = result.Groups(1).Value
End If
Next
It's not clear to me how your ListBoxes work. If you might find, for example, "Key 2:" inside ListBox1 that you need to ignore, you will want to change the [1-4] part of the expression to be more specific.
Additionally, if you're just trying to exclude unicode or punctuation, you could also go with ranges:
Dim keys As String = "A-Za-z0-9"
If you are supporting a broader set of characters, there are some you must be careful with: ], \, ^, and - can all have special meanings inside of a regular expression character class.
You have multiple keys, I assume you have multiple textboxes to display the results?
Then something like this would work. Loop thru the total number of keys, inside that you loop thru the alphabet. When you find a match, output to the correct textbox:
Dim UsersKey As String
For i As Integer = 1 To 4
For Each c In "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
UsersKey = c
If ListBox1.Items.Contains("Key" & i & ": " & UsersKey) Then
Select Case i
Case 1
TextBox1.Text = UsersKey
Case 2
TextBox2.Text = UsersKey
Case 3
TextBox3.Text = UsersKey
Case 4
TextBox4.Text = UsersKey
End Select
Exit For 'match found so exit inner loop
End If
Next
Next
Also, you say your settings are lost when the filename is changed. I assume when the version changes? The Settings has an upgrade method to read from a previous version. If you add an UpgradeSettings boolean option and set it to True and then do this at the start of your app, it will load the settings from a previous version:
If My.Settings.UpgradeSettings = True Then
My.Settings.Upgrade()
My.Settings.Reload()
My.Settings.UpgradeSettings = False
My.Settings.Save()
End If
Updated Answer:
Instead of using a listtbox, read the settings file line by line and output the results to the correct textbox based on the key...something like this:
Dim settingsFile As String = "C:\settings.txt"
If IO.File.Exists(settingsFile) Then
For Each line As String In IO.File.ReadLines(settingsFile)
Dim params() As String = Split(line, ":")
If params.Length = 2 Then
params(0) = params(0).Trim
params(1) = params(1).Trim
Select Case params(0)
Case "Key1"
Textbox1.Text = params(1)
Case "Key2"
Textbox2.Text = params(1)
End Select
End If
Next line
End If
You can associate text box with a key via its Name or Tag property. Lets say you use Name. In this case TextBox2 is associated with key2. TextBox[N] <-> Key[N]
Using this principle the code will look like this [considering that your list item is string]
Sub Test()
If ListBox1.SelectedIndex = -1 Then Return
Dim data[] As String = DirectCast(ListBox1.SelectedItem, string).Split(new char(){":"})
Dim key As String = data(0).Substring(3)
Dim val As String = data(1).Trim()
' you can use one of the known techniques to get control on which your texbox sits.
' I omit this step and assume "Surface1" being a control on which your text boxes sit
DirectCast(
(From ctrl In Surface1.Controls
Where ctrl.Name = "TextBox" & key
Select ctrl).First()), TextBox).Text = val
End Sub
As you can see, using principle I just explained, you have little parsing and what is important, there is no growing Select case if, lets say, you get 20 text boxes. You can add as many text boxes and as many corresponding list items as you wish, the code need not change.

Visual Basic Replace is not working

I am writing a simple hangman program and I want to replace something in my variable which stores the letters of the word that have been found.
Here is the code:
Replace(wordLettersFound, Mid(wordLettersFound, counter, 1), letter)
wordLettersFound, counter and letter are 3 of the variables I am using.
The variable is all underscores before this script, but it does not change! Can anyone help me with this?
P.S.
I do not know what version of VB I am using, visual studio community 2015 just says 'visual basic'.
Replace doesn't modify the string but returns a new string with the replacement so you should assign it to the variable:
wordLettersFound = Replace(wordLettersFound, Mid(wordLettersFound, counter, 1), letter)
Another way to do replace,
Dim theLetters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzAAA"
theLetters = theLetters.Replace("A"c, "#"c)
There is another way to replace a character in a string. Using the Replace function is a bit awkward in your case because, at the start, all the characters are underscores - Replace as you're using it will replace all of them with the found character.
Instead, you can cut up the string to the piece to the left of the desired replacement, add in the replacement character, and add on the rest of the string. That line is the one after the comment "chop foundWord up and put the character in the right place" in this code:
Module Module1
Sub Main()
Dim wordToFind = "alphabet"
' make a string of dashes the same length as the word to find
Dim foundWord = New String("-"c, wordToFind.Length)
While foundWord <> wordToFind
Console.Write("Enter your guess for a letter: ")
Dim guess = Console.ReadLine()
' make sure the user has only entered one character
If guess.Length = 1 Then
' see if the letter is in the string
Dim pos = wordToFind.IndexOf(guess)
While pos >= 0
' chop foundWord up and put the character in the right place
foundWord = foundWord.Substring(0, pos) & guess & foundWord.Substring(pos + 1)
' see if there are any more of the same letter
pos = wordToFind.IndexOf(guess, pos + 1)
End While
' show the user the current progress
Console.WriteLine(foundWord)
Else
Console.WriteLine("Please enter just one letter!")
End If
End While
Console.WriteLine("You did it!")
Console.WriteLine("Press enter to leave the program.")
Console.ReadLine()
End Sub
End Module
N.B. Do not use all that code directly for homework because your teacher will find this. And that goes to anyone else doing homework - you know who you are ;)

How to change my code to work a certain number of times?

My code gets a list of words from a txt file and chooses the words randomly. However, the same word can appear more than once and i need to know how to stop this from happening?
Here is the code:
Dim aryName As String() = Nothing
aryName = File.ReadAllLines(Application.StartupPath & "\Random\fnames.txt")
Dim randomWords As New List(Of String)
For i = 0 To aryName.Length - 1
If randomWords.Contains(aryName(i)) = False Then
randomWords.Add(aryName(i))
End If
Next
Dim random As New Random
Label2.Text = (randomWords(random.Next(0, randomWords.Count - 1)).ToString)
Maybe this might work, although it's in english and not code :(
if label1.text is changed then
Get label1.text
if label.text becomes this word again then
run the random code
end if
end if
This should prevent immediate repeats:
Dim random As New Random
'Just create a temporary holder for comparison
Dim word As String = Label2.Text
'Run a while loop that works as long as there
'is no change to the word. This should prevent
'back to back repeats.
While word = Label2.Text
word = (randomWords(random.Next(0, randomWords.Count - 1)).ToString)
End While
Label2.Text = word
If you don't want it to repeat ever again, you should probably remove the used word from the randomWords List.
Dim random As New Random
Label2.Text = (randomWords(random.Next(0, randomWords.Count - 1)).ToString)
randomWords.Remove(Label2.Text)
You can a) remove the selected word from the list, or b) you can random sort the list first.
Option a) is already addressed in another answer
Option b) lets you retain all the words in memory. Here is the code:
Dim randomWords As New List(Of String)(File.ReadAllLines(Application.StartupPath & "\Random\fnames.txt"))
Dim random As New Random
randomWords.Sort(Function(s1 As String, s2 As String) random.Next(-1, 1))
For index As Integer = 0 To randomWords.Count - 1
Label2.Text = randomWords(index)
Next
Modify your For loop to prevent dupes in aryName from getting into randomWords:
For i = 0 To aryName.Length - 1
If randomWords.Contains(aryName(i)) = False Then
randomWords.Add(aryName(i))
End If
Next