How to append an integer to an array in visual basic - vb.net

I'm making a program that takes a sentence with no punctuation as an input, then searches for how many occurrences there are of a specific word.
Dim sntnce As String
Dim srchWord As String
Dim words As String()
Dim word As String
Dim count As Integer
Dim index As New System.Text.StringBuilder()
Console.WriteLine("Enter your sentence: ")
sntnce = Console.ReadLine()
sntnce = LCase(sntnce)
Console.WriteLine("Enter the word you want to find the position of: ")
srchWord = Console.ReadLine()
srchWord = LCase(srchWord)
words = sntnce.Split(New Char() {" "c})
Console.WriteLine(" ")
For Each word In words
If word = srchWord Then
index.Append(count)
count += 1
Else
count += 1
End If
Next
Console.WriteLine("Your word appears in the position(s)...")
Console.WriteLine(index)
Console.ReadLine()
The for loop takes the index of a word if found in a sentence and appends it to a string, but I would like to append it to an array so that the values for indexes can be outputted separately, however I can't find any solutions that help. How can I do this? Thanks

Arrays are of fixed size only. When dealing with collections that you want to add, remove or insert use List(Of T).
I think what you want is the following:
Sub Main()
Dim sntnce As String
Dim srchWord As String
Dim words As String()
Dim word As String
Dim count As Integer
Console.WriteLine("Enter your sentence: ")
sntnce = Console.ReadLine()
sntnce = LCase(sntnce)
Console.WriteLine("Enter the word you want to find the position of: ")
srchWord = Console.ReadLine()
srchWord = LCase(srchWord)
words = sntnce.Split(New Char() {" "c})
Console.WriteLine(" ")
' Create an expandable list of integers 'index_list'
Dim index_list As New List(Of Integer)
For index As Integer = 1 To words.Length
' It's recommened to use `Equals()` for string equality instead of `=`
' Arrays in VB.NET are 0-based so the i-th elements is located in `list(i-1)`
If words(index - 1).Equals(srchWord) Then
' Add index to list if there is a match
index_list.Add(index)
End If
Next
' Create a fixed array of strings to hold the character representation of the integer index array.
' Since I know the size I can use an array instead of a list.
Dim index_list_string As String() = New String(index_list.Count) {}
For index As Integer = 1 To index_list.Count
' One to one mapping of integer to string
index_list_string(index - 1) = index_list(index - 1).ToString()
Next
Console.WriteLine("Your word appears in the position(s)...")
' Take the array of strings and combine it into one string with commas in between using the `.Join()` function
' For example `{"A","B","C"} => "A, B, C"
Console.WriteLine(String.Join(", ", index_list_string))
Console.ReadLine()
End Sub

Related

VB Check a Only Exactly Number in Textbox

Take a look at this picture. - http://www.imagebam.com/image/f544011007926944
I want to check in Textbox1, in the textbox2 enter the number and if there is that number I will appear in another text box. the problem occurs when in textbox1 there are numbers like 10,11, if I enter textbox2 number 1 then it will be taken as such, it will appear as if there is the number 1. I will only use for numbers from 1 to 80 .
where am I wrong?
' Split string based on space
Dim textsrtring As String = TextBox1.Text
Dim words As String() = textsrtring.Split(New Char() {" "c})
Dim found As Boolean = False
' Use For Each loop over words
Dim word As String
For Each word In words
If TextBox2.Lines(0).Contains(word) Then
found = True
If CheckVar1.Text.Contains(word) Then
Else
CheckVar1.Text = CheckVar1.Text + " " + TextBox1.Text()
End If
End If
So I think I know what you want. Your issue is the Compare Function on a String is comparing string literals and not numbers '11' contains '1' and '1' for Compare will return true that it contains a '1' in it. You need to convert the strings to numbers and then compare the numbers to each other.
Private Sub CompareNumbers()
'First Textbox that is to be used for compare
Dim textBox1Numbers As List(Of Integer) = GetNumbersFromTextLine(TextBox1.Text)
'Second Textbox that is to be used for compare
Dim textBox2Numbers As List(Of Integer) = GetNumbersFromTextLine(TextBox2.Text)
'Union List of Common Numbers (this uses a lambda expression, it can be done using two For Each loops instead.)
Dim commonNumbers As List(Of Integer) = textBox1Numbers.Where(Function(num) textBox2Numbers.Contains(num)).ToList()
'This is purely for testing to see if it worked you can.
Dim sb As StringBuilder = New StringBuilder()
For Each foundNum As Integer In commonNumbers
sb.Append(foundNum.ToString()).Append(" ")
Next
MessageBox.Show(sb.ToString())
End Sub
Private Function GetNumbersFromTextLine(sTextLine As String) As List(Of Integer)
Dim numberList As List(Of Integer) = New List(Of Integer)()
Dim sSplitNumbers As String() = sTextLine.Split(" ")
For Each sNumber As String In sSplitNumbers
If IsNumeric(sNumber) Then
Dim iNum As Integer = CInt(sNumber)
If Not numberList.Contains(iNum) Then
numberList.Add(iNum)
End If
Else
MessageBox.Show("Non Numeric Found in String :" + sTextLine)
End If
Next
Return numberList
End Function

Word and vowel count in VB 2017

I need to program a simple console application that takes an input string and then calls a sub routine to figure out the amount of words and the amount of vowels in the string. I've written this and for some reason it doesn't output the text I put in the Console.Writeline code. Any help on how to do this?
Module Module1
Sub Main()
Dim Sentence As String
Console.WriteLine("Sentence Analysis")
Console.WriteLine()
Console.WriteLine("Enter a sentence then press 'Enter'")
Console.WriteLine()
Sentence = Console.ReadLine()
Sentence = Sentence.ToUpper
Call Words(Sentence)
Call Vowels(Sentence)
Console.ReadLine()
End Sub
Sub Words(ByVal Input As String)
Dim Count As Integer
Dim Index As Short
Dim Character As Char
Do Until Index = Len(Input)
Character = Input.Substring(Index)
If Character = " " Then
Count = Count + 1
End If
Loop
Console.WriteLine("Your sentence contains {0} words.", (Count))
End Sub
Sub Vowels(ByVal Input As String)
Dim Count As Integer
Dim Vowels() As String = {"A", "E", "I", "O", "U"}
Dim Index As Short
Dim Character As Char
Do Until Index = Len(Input)
Character = Input.Substring(Index)
If Character = Vowels(Index) Then
Count = +1
End If
Loop
Console.WriteLine("Your sentence contains {0} words.", (Count))
End Sub
End Module
In Words you have the following code:
Do Until Index = Len(Input)
Index is never incremented and so loops infinitely.
Same issue in Vowels as well
Is the following any help to you?
Rather than looking at whether a sentence contains vowels, it looks at whether a list of vowels contains each character in the sentence.
For the word count, it similarly asks whether a string containing a single space contains each character in the sentence (the "word count" in this case is just a count of spaces, so leading or trailing spaces, or extra spaces between words, will be counted as extra words, as your code currently does).
It also allows us to abolish the separate method calls, and the hand-rolled looping code which, as you can see, are prone to small bugs (and I personally would recommend using a For loop rather than Do Until loop in this kind of situation, because For loops are designed to increment the index automatically).
Sub Main()
Console.WriteLine("Sentence Analysis")
Console.WriteLine()
Console.WriteLine("Enter a sentence then press 'Enter'")
Console.WriteLine()
Dim sentence As String
sentence = Console.ReadLine()
Dim vowel_count As Integer = sentence.Count(Function(c) "aeiou".Contains(Char.ToLower(c)))
Dim word_count As Integer = sentence.Count(Function(c) " ".Contains(Char.ToLower(c)))
Console.WriteLine("Your sentence contains {0} words.", word_count)
Console.WriteLine("Your sentence contains {0} vowels.", vowel_count)
Console.ReadLine()
End Sub
You go to the same college as I did. Here is the code...
Option Compare Text
Imports System
Imports System.Diagnostics.Metrics
Imports System.Reflection
Imports System.Text.RegularExpressions
Module Program
Sub Main(args As String())
Console.WriteLine("Sentence Analysis")
Console.WriteLine()
Console.WriteLine("Enter a sentence, then press 'Enter'")
Console.WriteLine()
Dim input As String = Console.ReadLine
Dim letterbyletter() As Char = input.ToCharArray
Dim counter As Integer = 1
Dim vowelcounter As Integer
Call wordcount(input, letterbyletter, counter)
Console.WriteLine("Your sentence contains {0} words.", counter)
Call vowelcount(input, letterbyletter, vowelcounter)
Console.WriteLine("Your sentence contains {0} vowels.", vowelcounter)
End Sub
Sub wordcount(ByVal input As String, ByRef letterbyletter() As Char, ByRef
counter As Integer)
For i = 0 To Len(input) - 1
If letterbyletter(i) = " " Then
counter += 1
End If
Next
End Sub
Sub vowelcount(ByVal input As String, ByRef letterbyletter() As Char, ByRef
vowelcounter As Integer)
Dim vowels() As String = {"a", "e", "i", "o", "u"}
For i = 0 To Len(input) - 1
For j = 0 To 4
If letterbyletter(i) = vowels(j) Then
vowelcounter += 1
End If
Next
Next
End Sub
End Module

Read words from a text file

I have a program that read words from a text file. My code works perfectly but why does it only read 1 word?
Code:
Public Function ReadFile1() As String
Dim text = IO.File.ReadAllText("APStringFile\file.txt")
' Counting words
Dim words = text.Split(" "c)
Dim wordCount As String
Dim Hasil As String
Dim FileStart As Integer = 0
Dim FileEnd As Integer = 100
For i As Integer = FileStart To FileEnd
wordCount = words(i)
'Hasil = wordCount(i)
Next i
Return wordCount
End Function
I want to read words from 0 to 100. But the result only read words in 100 count like this:
Can anyone help me solve my problem?
You can simplify your code with LINQ´s Skip and Take:
Public Function ReadFile1(FileStart As Integer, FileEnd As Integer) As String
Dim text = IO.File.ReadAllText("APStringFile\file.txt")
' Counting words
Dim words = text.Split(" "c)
'Skip the first n words then take m words
'where n = FileStart (e.g. 0) and m = delta between FileEnd (e.g. 100) and FileStart.
'Concat the result together to one string
Dim wordCount As String = String.Join(" ", words.Skip(FileStart).Take(FileEnd - FileStart).ToArray())
Return wordCount
End Function
Example usage:
Console.WriteLine(ReadFile1(0, 100)) 'Prints words 0 to 100
Console.WriteLine("---------")
Console.WriteLine(ReadFile1(101, 200)) 'Prints words 101 to 200
(I adjusted the ReadFile1 function so it takes the FileStart and FileEnd as parameters. This makes the usage a bit more dynamic. If you don´t want/need that just remove them and add them as local variables like you had before).
Edit: Explicit string declaration of wordCount variable
Eidt2: Added ToArray() due to .NET 3.5

How to indentify the positions that a word occurs in a given text?

I am developing a program where you can input a sentence and then search for a word. The program will then tell you at which positions this word occurs. I have written some code but do not know how to continue.
Module Module1
Sub Main()
Dim Sentence As String
Dim SentenceLength As Integer
Dim L As Integer = 0
Dim LotsofText As String = Console.ReadLine
Console.WriteLine("Enter your word ") : Sentence = Console.ReadLine
For L = 1 To LotsofText.Length
If (Mid(LotsofText, L, 1)) = " " Then
End If
L = L + 1
Dim TextCounter As Integer = 0
Dim MainWord As String = Sentence
Dim CountChar As String = " "
Do While InStr(MainWord, CountChar) > 0
MainWord = Mid(MainWord, 1 + InStr(MainWord, CountChar), Len(MainWord))
TextCounter = TextCounter + 1
'Text = TextCounter + 2
' Console.WriteLine(Text)
Loop
Console.WriteLine(TextCounter)
Console.Write("Press Enter to Exit")
Console.ReadLine()
End Sub
End Module
Transform this piece of code from C# to Visual Basic. match.Index will indicate the position of the given word.
var rx = new Regex("your");
foreach (Match match in rx.Matches("This is your text! This is your text!"))
{
int i = match.Index;
}
To find only words and not sub-strings (for example to ignore "cat" in "catty"):
Dim LotsofText = "catty cat"
Dim Sentence = "cat"
Dim pattern = "\b" & Regex.Escape(Sentence) & "\b"
Dim matches = Regex.Matches(LotsofText, pattern)
For Each m As Match In matches
Debug.Print(m.Index & "") ' 6
Next
If you want to find sub-strings too, you can remove the "\b" parts.
If you add this function to your code:
Public Function GetIndexes(ByVal SearchWithinThis As String, ByVal SearchForThis As String) As List(Of Integer)
Dim Result As New List(Of Integer)
Dim i As Integer = SearchWithinThis.IndexOf(SearchForThis)
While (i <> -1)
Result.Add(i)
i = SearchWithinThis.IndexOf(SearchForThis, i + 1)
End While
Return Result
End Function
And call the function in your code:
Dim Indexes as list(of Integer) = GetIndexes(LotsofText, Sentence)
Now GetIndexes will find all indexes of the word you are searching for within the sentence and put them in the list Indexes.

How do I create a loop statement that finds the specific amount of characters in a string?

Beginner here, bear with me, I apologize in advance for any mistakes.
It's some homework i'm having a bit of trouble going about.
Overall goal: outputting the specific amount of characters in a string using a loop statement. Example being, user wants to find how many "I" is in "Why did the chicken cross the road?", the answer should be 2.
1) The form/gui has 1 MultiLine textbox and 1 button titled "Search"
2) User enters/copys/pastes text into the Textbox clicks "Search" button
3) Search button opens an InputBox where the user will type in what character(s) they want to search for in the Textbox then presses "Ok"
4) (where I really need help) Using a Loop Statement, The program searches and counts the amount of times the text entered into the Inputbox, appears in the text inside the MultiLine Textbox, then, displays the amount of times the character showed up in a "messagebox.show"
All I have so far
Private Sub Search_btn_Click(sender As System.Object, e As System.EventArgs) Handles Search_btn.Click
Dim counterInt As Integer = 0
Dim charInputStr As String
charInputStr = CStr(InputBox("Enter Search Characters", "Search"))
I would use String.IndexOf(string, int) method to get that. Simple example of concept:
Dim input As String = "Test input string for Test and Testing the Test"
Dim search As String = "Test"
Dim count As Integer = -1
Dim index As Integer = 0
Do
index = input.IndexOf(search, index) + 1
count += 1
Loop While index > 0
count is initialized with -1 because of do-while loop usage - it will be set to 0 even if there is no pattern occurrence in input string.
Try this Code
Dim input As String = "Test input string for Test and Testing the Test"
Dim search() As String = {"Te"}
MsgBox(input.Split(input.Split(search, StringSplitOptions.None), StringSplitOptions.RemoveEmptyEntries).Count)
Concept: Increment the count until the input containing the particular search string. If it contains the search string then replace the first occurance with string.empty (In String.contains() , the search starts from its first index, that is 0)
Dim input As String = "Test input string for Test and Testing the Test"
Dim search As String = "T"
Dim count As Integer = 0
While input.Contains(search) : input = New Regex(search).Replace(input, String.Empty, 1) : count += 1 : End While
MsgBox(count)
Edit:
Another solution:
Dim Input As String = "Test input string for Test and Testing the Test"
Dim Search As String = "Test"
MsgBox((Input.Length - Input.Replace(Search, String.Empty).Length) / Search.Length)
try this code.... untested but i know my vb :)
Function lol(ByVal YourLine As String, ByVal YourSearch As String)
Dim num As Integer = 0
Dim y = YourLine.ToCharArray
Dim z = y.Count
Dim x = 0
Do
Dim l = y(x)
If l = YourSearch Then
num = num + 1
End If
x = x + 1
Loop While x < z
Return num
End Function
Its a function that uses its own counter... for every character in the string it will check if that character is one that you have set (YourSearch) and then it will return the number of items that it found. so in your case it would return 2 because there are two i's in your line.
Hope this helps!
EDIT:
This only works if you are searching for individual Characters not words
You can try with something like this:
Dim sText As String = TextBox1.Text
Dim searchChars() As Char = New Char() {"i"c, "a"c, "x"c}
Dim index, iCont As Integer
index = sText.IndexOfAny(searchChars)
While index >= 0 Then
iCont += 1
index = sText.IndexOfAny(searchChars, index + 1)
End While
Messagebox.Show("Characters found " & iCont & " times in text")
If you want to search for words and the times each one is appearing try this:
Dim text As String = TextBox1.Text
Dim wordsToSearch() As String = New String() {"Hello", "World", "foo"}
Dim words As New List(Of String)()
Dim findings As Dictionary(Of String, List(Of Integer))
'Dividing into words
words.AddRange(text.Split(New String() {" ", Environment.NewLine()}, StringSplitOptions.RemoveEmptyEntries))
findings = SearchWords(words, wordsToSearch)
Console.WriteLine("Number of 'foo': " & findings("foo").Count)
With this function used:
Private Function SearchWords(ByVal allWords As List(Of String), ByVal wordsToSearch() As String) As Dictionary(Of String, List(Of Integer))
Dim dResult As New Dictionary(Of String, List(Of Integer))()
Dim i As Integer = 0
For Each s As String In wordsToSearch
dResult.Add(s, New List(Of Integer))
While i >= 0 AndAlso i < allWords.Count
i = allWords.IndexOf(s, i)
If i >= 0 Then dResult(s).Add(i)
i += 1
End While
Next
Return dResult
End Function
You will have not only the number of occurances, but the index positions in the file, grouped easily in a Dictionary.