Read every fourth line from a text file - vb.net

So, I have a text file with the following:
Andrew Law
0276376352
13 Parsons St
Kevin Kyle
0376458374
29 Penrod Drive
Billy Madison
06756355
16 Stafford Street
Now on my Form, I have a ListBox. When the Form loads, I would like to read every fourth line from the text file (every name) and display it in the ListBox.
All I have right now is the following:
Dim People As String
People = System.IO.File.ReadAllLines("filelocation")(3)
ListBox1.Items.Add(People)
This however only reads line number 4 where as I want to read EVERY fourth line after that also.

Add all the strings extracted from a source file, when the current line is a multiple of a pre-defined number of lines to skip or 0, to a ListBox and allow a user to select a Name from the list to fill some Labels with the details related to the selected Name.
Parse and extract the People Names from the array of string. Each Name can be found at an index which is multiple of the value specified by the skipLines field.
Add each Name to a ListBox control.
When a Name is selected from the ListBox list of names, add the related details to some Labels (named lblPhoneNumber and lblAddress here). To identify the correct informations in the array, we're using the skipLines value as a multiplier this time. This way, even if you add some more details in the list of names, you'll find the right informations modifying just the skipLines value.
You need to subscribe to the SelectedIndexChanged event of the ListBox:
Public Class Form1
Private people As String()
Private skipLines As Integer = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
skipLines = 3
people = File.ReadAllLines([Source File])
For line As Integer = 0 To people.Length - 1
If line Mod skipLines = 0 Then
ListBox1.Items.Add(people(line))
End If
Next
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim StartIndex As Integer = ListBox1.SelectedIndex * skipLines
lblPhoneNumber.Text = people(StartIndex + 1)
lblAddress.Text = people(StartIndex + 2)
End Sub
End Class
How this works:
Define the number of lines to skip. We want a line of text, then skip 3 lines, here:
Dim skipLines As Integer = 3
We create an array of strings. It will contain the output of File.ReadAllLines(), which of course returns an array of strings:
Dim people As String() = File.ReadAllLines([Source File])
Iterate the whole content of the array of strings, line by line. A collection enumeration starts from 0, so we parse the list from 0 to the number of elements - 1:
For line As Integer = 0 To people.Length - 1
'[...]
Next
The If condition if met when the current line number is a multiple of skipLines.
The Mod operator divides two numbers and returns the remainder of the operation. If there's no reminder, the line number is a multiple of skipLines, the number of lines we want to skip.
If line Mod skipLines = 0 Then
`[...]
End If
Finally, when the condition is met, add the content of the array of strings (the people array) at the index represented by the current line value, to the ListBox.Items collection:
ListBox1.Items.Add(people(line))

Related

How can calculate the number of columns in a textfile and show in a textbox, in vb.net?

I have a textfile (data.txt) with 3 columns, each column with one variable (x1, x2 and x3). I would like to calculate a number of columns and show in a specific textbox (like textbox1).
For example. My data.txt:
x1 x2 x3
10 15 20
20 10 10
TextBox1 needs to show: 3
Text files don't have columns. What you have is a file where each line separates elements by a space and each row is separated by a CR/LF (carraige return/line feed) To work with the text file put
Imports System.IO
at the top of the code file.
I am guessing that you will want to do more with the file than just determin the number of "columns" so, we will read the entire file. File.ReadAllLines() returns an array of lines in the file.
We take the first line in the file (index 0) and split it by a space. The lowere case c followint " " tells the compiler that you mean a Char not a String. Then we take the Length of the resulting array to find the number of columns.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lines = File.ReadAllLines("C:\Users\******\Desktop\Code\OPdata.txt")
Dim NoOfColumns = lines(0).Split(" "c).Length
TextBox1.Text = NoOfColumns.ToString
'Some other things you can do
Dim dt As New DataTable
Dim columns = lines(0).Split(" "c)
dt.Columns.Add(columns(0), GetType(Integer))
dt.Columns.Add(columns(1), GetType(Integer))
dt.Columns.Add(columns(2), GetType(Integer))
For index = 1 To lines.Length - 1
Dim values = lines(index).Split(" "c)
dt.Rows.Add({values(0), values(1), values(2)})
Next
DataGridView1.DataSource = dt
End Sub
You might want to consider using Microsoft.VisualBasic.FileIO.TextFieldParser. It's designed to process structured text files (either delimited or fixed-width) and will remove some of the necessary ceremony compared with direct file I/O as in Mary's answer. Note that TextFieldParser implements IDisposable, so it should either be used within a Using block or disposed manually.
FileOpen(1, "data.txt", OpenMode.Input)
line1$ = LineInput(1) 'get first line
FileClose(1)
TextBox1.Text = UBound(Split(line1, " ")) + 1

VB windows form calculate the digit in a multiline textbox

I want to calculate each line: it's like first line 123*1.616 and the second line 213*1.616, and display each total.
Every number entred in the kilogram textbox will mutiply 1.616 and then show the result in the kati label.
Here is my code:
Private Sub b1_Click(sender As Object, e As EventArgs) Handles b1.Enter
For Each digit In (TextBox1.Text)
total1 = Val(digit) * 1.616
Label9.Text = total1
Next
Label9.Text = total1
End sub
Please help me find some solution or explanation to achieve the output.
This should work
Private FACTOR As Decimal = 1.616
Private SEPARATOR As String = Environment.NewLine
Private Sub b1_Click(sender As Object, e As EventArgs) Handles b1.Click
Label9.Text = TextBox1.Text.
Split({SEPARATOR}, StringSplitOptions.RemoveEmptyEntries).
Select(Function(s1) $"{Decimal.Parse(s1) * FACTOR:0.00#}").
Aggregate(Function(s1, s2) $"{s1}{SEPARATOR}{s2}")
End Sub
Here are the functions in the LINQ
Split makes an array out of each line in the TextBox using SEPARATOR as the delimiter
Select transforms the elements into their value times FACTOR
Aggregate puts the elements back together into a SEPERATOR delimited string
Why didn't your original code work?
You were iterating over each char in the text, and multiplying the char by a float (Option Strict On, as suggested in the comments would have prevented that).
Then in each iteration, you do (simplified) Label9.Text = Val(digit) * 1.616 which overwrites the Label every time.
If you were to step through in debug (also suggested in comments), you would see the Label becoming 1x1.616=1.616, 2x1.616=3.232, 3x1.616=4.848, etc. The result was the very last character in your TextBox, '3', times 1.161 = 4.848. Obviously, this was not what you wanted. You needed to instead iterate over each entire number. The multiline TextBox separates each line with a new line. So we iterate over each line instead.
you can use split string by vbCrLf
Sub main()
Dim multilinetext As String =
"10
20
30
40
50
60"
Dim number_array = multilinetext.Split(vbCrLf)
Dim output As Integer = 0
For Each i In number_array
output += i
Next
Stop
End Sub

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 to search for a word that contains uppercase and lowercase letters in a TextBox and then replace it with another word [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a TextBox that includes more words
Example:
I'm pRoFeSSoinaL coder
I want to search for the word pRoFeSSoinaL (that contains uppercase and lowercase letters) and then replace it.
OK let me try and address your problem again based on your image:
And on your comment:
...but i need search about word have More than a change of letters example (execute, ExEcute, eXecute, execUtE........ETC) i need find word No matter how large and small the letters are see this proof
Again, if I have this right, you would like to find all occurrences of a word regardless of it's case. In effect you would like for your application to work a bit like Notepad.
I've put together some code that will use the following methods:
String.ToLower:
Returns a copy of this string converted to lowercase.
TextBox.Select:
Selects a range of text in the text box.
String.Remove:
Returns a new string in which a specified number of characters in the current instance beginning at a specified position have been deleted.
String.Insert:
Returns a new string in which a specified string is inserted at a specified index position in this instance.
String.Substring:
Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.
I have three Button controls that I've put a bit a code behind. One will find the next occurrence of a word, another will replace the next occurrence of a word and the last one will replace all occurrences of a word.
Now it's not my job to design your application but for ease I have also popped on three TextBox controls. This is how my form looks:
To find the next occurrence of professional this is the code I used:
Private Sub btnFindNext_Click(sender As Object, e As EventArgs) Handles btnFindNext.Click
'check word exists
If txtTextToSearch.Text.ToLower().Contains(txtWordToFind.Text.ToLower()) Then
'reset position if at end of text
If txtTextToSearch.Text.ToLower().IndexOf(txtWordToFind.Text.ToLower(), position + 1) < 0 Then
position = 0
End If
'set position of next occurrence
position = txtTextToSearch.Text.ToLower().IndexOf(txtWordToFind.Text.ToLower(), position + 1)
'select next occurrence
txtTextToSearch.Select(position, txtWordToFind.Text.Length)
End If
End Sub
This is a screenshot of how it would look when you click the button:
Clicking the button again will select the next occurrence of the word. It will keep toggling between the two in my example.
To replace the next occurrence of professional this is the code I used:
Private Sub btnReplaceNext_Click(sender As Object, e As EventArgs) Handles btnReplaceNext.Click
'check word exists
If txtTextToSearch.Text.ToLower().Contains(txtWordToFind.Text.ToLower()) Then
'reset position if at end of text
If txtTextToSearch.Text.ToLower().IndexOf(txtWordToFind.Text.ToLower(), position + 1) < 0 Then
position = 0
End If
'set position of next occurrence
position = txtTextToSearch.Text.ToLower().IndexOf(txtWordToFind.Text.ToLower(), position + 1)
'remove old word
txtTextToSearch.Text = txtTextToSearch.Text.Remove(position, txtWordToFind.Text.Length())
'insert new word
txtTextToSearch.Text = txtTextToSearch.Text.Insert(position, txtReplaceWith.Text)
End If
End Sub
This is a screenshot of how it would look when you click the button:
Clicking the button again will replace the next occurrence of the word.
To replace all occurrences of the word professional this is the code I used:
Private Sub btnReplaceAll_Click(sender As Object, e As EventArgs) Handles btnReplaceAll.Click
'check word exists
If txtTextToSearch.Text.ToLower().Contains(txtWordToFind.Text.ToLower()) Then
'reset position if at end of text
If txtTextToSearch.Text.ToLower().IndexOf(txtWordToFind.Text.ToLower(), position + 1) < 0 Then
position = 0
End If
'set position of next occurrence
position = txtTextToSearch.Text.ToLower().IndexOf(txtWordToFind.Text.ToLower(), position + 1)
While position > 0 AndAlso position < txtTextToSearch.Text.Length
'remove old word
txtTextToSearch.Text = txtTextToSearch.Text.Remove(position, txtWordToFind.Text.Length())
'insert new word
txtTextToSearch.Text = txtTextToSearch.Text.Insert(position, txtReplaceWith.Text)
'set position of next occurrence
position = txtTextToSearch.Text.ToLower().IndexOf(txtWordToFind.Text.ToLower(), position + 1)
End While
End If
End Sub
This is a screenshot of how it would look when you click the button:
My code will need adapting I'm sure but it should give you something to go on. As for the level of detail I have gone to, may not benefit you but may benefit others that visit this question. Hope this helps.
Judging from your screenshot (http://i.imgur.com/77wdZoI.png) you appear to be after case-insensitive string matching.
The simplest way is to use the String.IndexOf(String, StringComparison) overload to perform case-insensitive comparison:
Private Function FindText(ByVal Source As String, ByVal Text As String) As Integer
Return Source.IndexOf(Text, StringComparison.OrdinalIgnoreCase)
End Function
Usage example:
Dim TextToFind As String = "professional"
Dim TextPos As Integer = FindText(TextBox1.Text, TextToFind)
If TextPos > -1 Then 'Match found.
TextBox1.SelectionStart = TextPos
TextBox1.SelectionLength = TextToFind.Length
End If

VB.NET - How to format text boxes so they divide the text into chunks of n letters?

I have two text boxes, that can only contain capital letters, and a variable where I store an unsigned integer. Let's say for instance 5. How can I make it so that my TextBoxes that contain random text are split into groups of 5 letter?
For example: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Becomes: ABCDE FGHIJ KLMNO PQRST UVWXY Z
I need this to be done in real time in case the text is replaced by the user. I also cannot use multiple text boxes that allow n characters each as the text I'm supposed to format can be indefinitely long.
You can use this approach for every time the Textbox.Text changes:
Private Sub Textbox1_TextChanged(sender As Object, e As EventArgs) Handles Textbox1.TextChanged
Dim sentence As String = Textbox1.Text
Dim pairedChars as Integer = 5
If pairedChars <= sentence.Length Then
'First remove all spaces from the last time
sentence.Replace(" ", "")
'Add spaces at every 5th place in the string
For i = 1 to (sentence.Length) / pairedChars
sentence = sentence.Insert(i * pairedChars + (i - 1), " ")
Next
End If
End Sub