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
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 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
i'm in the making of machine readable dictionary for my native language which is Malay. i need to extract the Malay translation from the .txt file. In the .txt file, the example are like this:
aberration : aberasi
aberration function : rangkap aberasi
ablation : ablasi
ablative material : bahan ablasi
the left one are the terms in English and after the separator : is Malay.
What I would like to ask is how do i do when the word search is "aberration function" and i need to display only "rangkap aberasi"?
i tried to used
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim text As String = "dictionary.txt"
Dim word As String = "\b" & TextBox2.Text & "\b\s+(\w+)"
For Each a As Match In Regex.Matches(text, word, RegexOptions.IgnoreCase)
MsgBox(a.Groups(1).Value)
Next
End Sub
End Class
See more at: http://www.visual-basic-tutorials.com/get-the-next-word-after-a-specific-word-in-visual-basic.htm#sthash.w8E1Qb6l.dpuf
however, my problem is, this code above only display the next word after seperation which is "rangkap". while i need the whole text after separation ":" which might be more than 2 words.
here is my current code
Using reader As New StreamReader("D:\Dictionary of Engineering A only.txt")
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
If line.Contains(wordsearch.Text) Then
Edef.Text = line
Exit While
End If
End While
End Using
One way to solve this would be like this:
Using reader As New StreamReader("D:\Dictionary of Engineering A only.txt")
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
If line.Contains(wordsearch.Text) Then
dim lineParts() as String = line.split(":")
Edef.Text = lineParts(1)
Exit While
End If
End While
End Using
You check if the line contains the text, if so, you split the line by the ":" and take the 2nd part of it.
I want to be able so get the ASCII values of all the characters in a string.
I can get the ASCII value of a character but i cannot do it for the whole string.
My attempt:
dim input as string = console.readline()
dim value as integer = ASC(input)
'Then I am changing its value by +1 to write the input in a secret code form.
console.writeline(CHR(value+1))
I want to be able to get the ASCII values for all characters in the string so i can change the all letters in the string +1 character in the alphabet.
Any help appreciated, thanks.
Use Encoding.ASCII.GetBytes:
Dim asciis As Byte() = System.Text.Encoding.ASCII.GetBytes(input)
If you want to increase each letter's ascii value you can use this code:
For i As Int32 = 0 To asciis.Length - 1
asciis(i) = CByte(asciis(i) + 1)
Next
Dim result As String = System.Text.Encoding.ASCII.GetString(asciis)
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
Dim a As Integer
a = Asc(TextBox1.Text)
MessageBox.Show(a)
End Sub
End Class
I know it's been almost three years now, but let me show you this.
Function to convert String to Ascii (You already have a String in your Code). You can use either (Asc) or (Ascw) ... for more information, please read Microsoft Docs
Dim Input As String = console.readline()
Dim Value As New List(Of Integer)
For Each N As Char In Input
Value.Add(Asc(N) & " ")
Next
Dim OutPutsAscii As String = String.Join(" ", Value)
Function to Convert Ascii to String (What you asked for). You can use either (Chr) or (ChrW) ... for more information, please read Microsoft Docs
Dim Value1 As New List(Of Integer)
Dim MyString As String = String.Empty
For Each Val1 As Integer In Value1
MyString &= ChrW(Val1)
Next
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