VB Check a Only Exactly Number in Textbox - vb.net

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

Related

Find Value as Integer in a Textbox

I would need a little help. If in the Textbox - TxtStringNum1.Text - we have the Digit 3. and TxtIntDraws.Lines (1) - contains the following set: 13,20,21,23,47,49,50,51,63,64,66,70
It shows me that there is Exists a Digit of 3, but it is actually the Digits of 13. It fails to look for it as a whole.
Private Sub ScanareLinia1()
Dim textsrtring As String = TxtStringNum1.Text
Dim words As String() = textsrtring.Split(New Char() {" "c})
' Split string based on space
Dim found As Boolean = False
' Use For Each loop over words
Dim word As Integer
For Each word In words
For i As Integer = 0 To TxtIntDraws.Lines.Count - 1
If TxtIntDraws.Lines(1).Contains(word) Then
TxtResultStr1.Text = word
End If
Next
Next
ScanareLinia2()
End Sub
I have a good comparison code, but I do not know how to use it for the code above.
Private Sub CompareNumbers()
'Pentru funcția de Check-In (For Match Exactly Value Number in List)
'First Textbox that is to be used for compare
Dim textBox1Numbers As List(Of Integer) = GetNumbersFromTextLine(TxtStringNum1.Text)
'Second Textbox that is to be used for compare
Dim textBox2Numbers As List(Of Integer) = GetNumbersFromTextLine(TxtbValBeforeCompar.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(TextBox25.Text)
TxtbValAfterCompar.Text = (sb.ToString())
Next
End Sub
Private Function GetNumbersFromTextLine(ByVal sTextLine As String) As List(Of Integer)
'Pentru funcția de Check-In (For Match Exactly Value Number in List)
Dim numberList As List(Of Integer) = New List(Of Integer)()
Dim sSplitNumbers As String() = sTextLine.Split(TextBox8.Text)
For Each sNumber As String In sSplitNumbers
If IsNumeric(sNumber) Then
Dim iNum As Integer = CInt(sNumber)
TxtbValAfterCompar.Text = iNum
If Not numberList.Contains(iNum) Then
TxtbValAfterCompar.Text = ("")
numberList.Add(iNum)
End If
Else
End If
Next
Return numberList
End Function
You can use the following condition using String.Split and Array.IndexOf:
If Array.IndexOf(TxtIntDraws.Lines(1).Split(","c), CStr(word)) > -1 Then
TxtResultStr1.Text = word
End If
So the following Array.IndexOf(CStr("13,14,15,16,17").Split(","c), "13") > -1 is True and Array.IndexOf(CStr("13,14,15,16,17").Split(","c), "3") > -1 is False.

How to append an integer to an array in visual basic

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

How to store 2 of the same item in a dictionary

I need to store the same item twice in a dictionary because say I have this sentence: 'Hi Example Test Hi' This should output 1, 2, 3, 1 as it needs to store the initial position with the word. Here is the code I have so far:
If System.Text.RegularExpressions.Regex.IsMatch(userInput.Text, "^[a-zA-Z\s]+$") Then
Dim userString As String = userInput.Text 'Refers to the textbox's text.
Dim count As Integer 'Declares the count variable, which will be added to the dictionary as the word's position.
Dim d As New Dictionary(Of String, Integer) 'Declares the dictionary I will iterate through in the future.
Dim d2 As New Dictionary(Of String, Integer)
Dim wordString = userString.ToLower().Split(" "c) 'Puts the input into lower case and splits it apart by detecting each space after each word.
For Each word In wordString
If (d.ContainsKey(word)) Then
Else
d.Add(word, count) 'Adds each word to the dictionary along with the position.
count = count + 1 'Adds to the count variable to iterate through the dictionary.
End If
Next
For Each de In d
For Each dee In d2
output.Text &= de.Value + 1 & ", " & dee.Value + 1 & ", " & Environment.NewLine 'Gathers each word from the dictionary, referencing it by using 'de' and retrieving the key and value.
Next
Next
Else
MessageBox.Show("Your Sentence Is Invalid, It Must Only Contains Letters.") 'Displays a message if the sentence they inputted is invalid.
End If
thanks,
Matt
maybe something like this:
Dim userString As String = "Hi Example Test Hi"
Dim count As Integer = 1 'Declares the count variable, which will be added to the dictionary as the word's position.
Dim d As New List(Of WordCountPos) 'Declares the dictionary I will iterate through in the future.
Dim wordString = userString.ToLower().Split(" "c) 'Puts the input into lower case and splits it apart by detecting each space after each word.
For Each word In wordString
If d.FindIndex(Function(x) String.Equals(x.Word, word)) <> -1 Then
d.Find(Function(x) String.Equals(x.Word, word)).Positions.Add(count)
Else
d.Add(New WordCountPos(word, 1, New List(Of Integer)({count}))) 'Adds each word to the dictionary along with the position
End If
count = count + 1 'Adds to the count variable to iterate through the dictionary.
Next
Dim output As String = ""
For Each de In d
output = String.Concat(output, Environment.NewLine, "Word: ", de.Word, " Count: ", de.Count, ", Positions:", String.Join("|", de.Positions.ToArray))
Next
Console.WriteLine(output)
Class:
Public Class WordCountPos
Public Sub New(w As String, c As String, pos As List(Of Integer))
Me.wcp_w = w
Me.wcp_c = c
Me.wcp_pos = pos
End Sub
Private wcp_w As String
Public Property Word() As String
Get
Return wcp_w
End Get
Set(ByVal value As String)
wcp_w = value
End Set
End Property
Private wcp_c As Integer
Public Property Count() As Integer
Get
Return wcp_c
End Get
Set(ByVal value As Integer)
wcp_c = value
End Set
End Property
Private wcp_pos As List(Of Integer)
Public Property Positions() As List(Of Integer)
Get
Return wcp_pos
End Get
Set(ByVal value As List(Of Integer))
wcp_pos = value
End Set
End Property
End Class

permutation not accepting large words

the vb.net code below permutates a given word...the problem i have is that it does not accept larger words like "photosynthesis", "Calendar", etc but accepts smaller words like "book", "land", etc ...what is missing...Pls help
Module Module1
Sub Main()
Dim strInputString As String = String.Empty
Dim lstPermutations As List(Of String)
'Loop until exit character is read
While strInputString <> "x"
Console.Write("Please enter a string or x to exit: ")
strInputString = Console.ReadLine()
If strInputString = "x" Then
Continue While
End If
'Create a new list and append all possible permutations to it.
lstPermutations = New List(Of String)
Append(strInputString, lstPermutations)
'Sort and display list+stats
lstPermutations.Sort()
For Each strPermutation As String In lstPermutations
Console.WriteLine("Permutation: " + strPermutation)
Next
Console.WriteLine("Total: " + lstPermutations.Count.ToString)
Console.WriteLine("")
End While
End Sub
Public Sub Append(ByVal pString As String, ByRef pList As List(Of String))
Dim strInsertValue As String
Dim strBase As String
Dim strComposed As String
'Add the base string to the list if it doesn't exist
If pList.Contains(pString) = False Then
pList.Add(pString)
End If
'Iterate through every possible set of characters
For intLoop As Integer = 1 To pString.Length - 1
'we need to slide and call an interative function.
For intInnerLoop As Integer = 0 To pString.Length - intLoop
'Get a base insert value, example (a,ab,abc)
strInsertValue = pString.Substring(intInnerLoop, intLoop)
'Remove the base insert value from the string eg (bcd,cd,d)
strBase = pString.Remove(intInnerLoop, intLoop)
'insert the value from the string into spot and check
For intCharLoop As Integer = 0 To strBase.Length - 1
strComposed = strBase.Insert(intCharLoop, strInsertValue)
If pList.Contains(strComposed) = False Then
pList.Add(strComposed)
'Call the same function to review any sub-permutations.
Append(strComposed, pList)
End If
Next
Next
Next
End Sub
End Module
Without actually creating a project to run this code, nor knowing how it 'doesn't accept' long words, my answer would be that there are a lot of permutations for long words and your program is just taking much longer than you're expecting to run. So you probably think it has crashed.
UPDATE:
The problem is the recursion, it's blowing up the stack. You'll have to rewrite your code to use an iteration instead of recursion. Generally explained here
http://www.refactoring.com/catalog/replaceRecursionWithIteration.html
Psuedo code here uses iteration instead of recursion
Generate list of all possible permutations of a string

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.