Count a specific string in a multiline textbox (VB.Net) - vb.net

I very much want to count the values in a multiline textbox each time each value appears in descending order> in ascending order. I tried a lot but nothing works as it should. (VB.Net)
Textbox1.Lines
2
3
2
2
4
7
7
7
28
28
Expected Output: Textbox2.Lines
2 = Count = 3
7 = Count = 3
28 = Count = 2
3 = Count = 1
4 = Count = 1
What i try and dind't worked.
#1
Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
Dim cnt As Integer = 0
For Each c As Char In value
If c = ch Then
cnt += 1
End If
Next
Return cnt
End Function
#2
Dim a As String = "this is test"
Dim pattern As String = "t"
Dim ex As New System.Text.RegularExpressions.Regex(pattern)
Dim m As System.Text.RegularExpressions.MatchCollection
m = ex.Matches(a)
MsgBox(m.Count.ToString())
#3
Public Shared Function StrCounter(str As String, CountStr As String) As Integer
Dim Ctr As Integer = 0
Dim Ptr As Integer = 1
While InStr(Ptr, str, CountStr) > 0
Ptr = InStr(Ptr, str, CountStr) + Len(CountStr)
Ctr += 1
End While
Return Ctr
End Function

You need to remember which strings have already appeared and then count them. To do that, you can use a dictionary.
Dim dict_strCount As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)()
' Run over each line in the input
For Each line As String In tb_yourTextBox.Text.Lines
' Check if we have already counted the string in this line
If dict_strCount.ContainsKey(line) Then
dict_strCount(line) += 1 ' if so, increment that count
Else
dict_strCount.Add(line, 1) ' if not, add it to the dictionary (with count of 1)
End If
Next
tb_yourOutputTextBox.Text = String.Empty ' clear the output
' run over all the elements in the dictionary in ascending order by value
' and output to the output textbox
For Each kvp As KeyValuePair(Of String, Integer) In dict_strCount.OrderBy(Function(x) x.Value)
tb_yourOutputTextBox.Text += kvp.Key & ": " & kvp.Value.ToString() & vbNewLine
Next
You may test it here

Related

How can put split integers in a two-dimensional array?

I making matrix calculator. so, Textbox_A contains vbCrLf and tries to put it in Array_A.
and I would like to put Array_A in Result Matrix.
It's like
Textbox_a:
(1 2 3)
(4 5 6)
[Matrix to Array]
Array_a(0)(0) = 1
Array_a(0)(1) = 2
Array_a(0)(2) = 3
Array_a(1)(0) = 4
...
I have done string splits through several articles, but changing them to integers causes many problems.
This picture is Matrix_A and result Matrix
I don't know if the size of your initial matrix, formatted as text, is fixed, but here is some code to help you get started. The code tries to calculate the number of columns and rows.
The actual code is in the TextToArray function, that takes as input as string formatted as you described:
(1 2 3) (cr/lf)
(4 5 6)
and outputs a two dimensional array. The Main sub is just used to call TextToArray and display results.
So, in your example, you should pass TextBox_A.Text to TextToArray
There is minimal error checking here - you should add more to validate that data entered are numbers (check the Integer.TryParse function) and that the number of columns is the same across lines.
Sub Main(args As String())
Dim myInput As String = "(1 2 3)" & vbCrLf & "(4 5 6)"
Dim ret As Integer(,) = TextToArray(myInput)
If ret IsNot Nothing Then
For i As Integer = 0 To ret.GetUpperBound(0) - 1
For n As Integer = 0 To ret.GetUpperBound(1) - 1
Console.WriteLine(i & "," & n & "=" & ret(i, n))
Next
Next
Else
Console.WriteLine("No results - wrong input format")
End If
Console.ReadLine()
End Sub
Private Function TextToArray(matrix As String) As Integer(,)
Dim noOfRows As Integer = matrix.Split(vbCrLf).Count
Dim noOfColumns As Integer = 0
If noOfRows > 0 Then
noOfColumns = matrix.Split(vbCrLf)(0).Split(" ").Count
End If
If noOfColumns > 0 And noOfRows > 0 Then
Dim ret(noOfRows, noOfColumns) As Integer
Dim lines As String() = matrix.Split(vbCrLf)
Dim row As Integer = 0
For Each line As String In lines
Dim col As Integer = 0
line = line.Replace("(", "")
line = line.Replace(")", "")
For Each s As String In line.Split(" ")
ret(row, col) = Integer.Parse(s)
col += 1
Next
row += 1
Next
Return ret
Else
Return Nothing
End If
End Function
This outputs:
0,0=1
0,1=2
0,2=3
1,0=4
1,1=5
1,2=6

Random generate numbers and letters based on 2 symbols as letters and numbers and using a -

This is a number #
This is a number or letter?
Separate the random string like ??#?#-???##-#?#???-#???#-##
I need some code that generates the string as shown above. It doesn't have to be complicated.
Expected result example: 2F421-QD421-2W3FY0-3F4L1-37
I've tried using PHP and this example but wasn't able to achieve what I was looking for Generating a random numbers and letters
I am looking for a vb.net project to handle the generation so i can submit the serial into a database manually.
I quite like this approach:
Dim characters = "0123456789ABCDEFGHIJKLOMNOPQRSTUVWXYZ"
Dim template = "??#?#-???##-#?#???-#???#-##"
Dim rnd = New Random()
Dim query =
From t In template
Select If(t = "-", "-", characters(rnd.Next(If(t = "?", characters.Length, 10))))
Dim result = String.Join("", query)
Console.WriteLine(result)
It gives me output like this:
RC2C9-DHB47-1Q07RL-8BIF7-57
Create 2 functions 1 for letters GRL (Generate Random Letter) 1 for numbers GRN (Generate Random Number) like so:
Result of what i called is: W96-GKlF6
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Console.WriteLine(GRL(1) + GRN(2) + "-" + GRL(4) + GRN(1))
End Sub
Public Function GRL(ByRef iLength As Integer) As String
Static rdm As New Random()
Dim allowChrs() As Char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ".ToCharArray()
Dim sResult As String = String.Empty
For i As Integer = 0 To iLength - 1
sResult += allowChrs(rdm.Next(0, allowChrs.Length))
Next
Return sResult
End Function
Public Function GRN(ByRef iLength As Integer) As String
Static rdm As New Random()
Dim allowChrs() As Char = "0123456789".ToCharArray()
Dim sResult As String = String.Empty
For i As Integer = 0 To iLength - 1
sResult += allowChrs(rdm.Next(0, allowChrs.Length))
Next
Return sResult
End Function
Easy, random numbers to use as ASCII codes, then check the position to delimit if its going to be just a number or a character that can be number or letter.
When is a position that can be number or letter, analyze the random number and split it. If the number is less than 11 that means is a number then add 47 and use the result as ASCII code (random create numbers from 1 to 36) so for example if the random is 1, we say 47 + 1 = 48, 48 is the ASCII code of 0.
If the number is 11 or more we add 54, so for example if random is 11 then we have 11 + 54 = 65. 65 is the ASCII code for the letter A.
Dim Key As String = ""
Dim N As Integer
Randomize()
For t = 1 To 23
If t = 3 Or t = 5 Or t = 9 Or t = 10 Or t = 11 Or t = 13 Or t = 17 Or t >= 21 Then
N = 10
Else
N = 36
End If
Dim value As Integer = CInt(Int(N * Rnd() + 1))
If value < 11 Then
Key = Key & Chr(value + 47)
Else
Key = Key & Chr(value + 54)
End If
If t = 5 Or t = 10 Or t = 16 Or t = 21 Then
Key = Key & "-"
End If
Next

Get the number of occurrences out of textbox

Hi I'm trying to get the number of occurrences of a character out of a txtbox. Still haven't found the answer...
For example:
I give in a sentence... "Hello there!." and in a listbox there must be...
H - 2 times
e - 3 times
....
this is my code...
For i = 0 To txtSent.Text.Length - 1
If (Char.IsLetter(txtSent.Text(i))) Then
Dim str = Len(txtSent.Text) - Len(Replace(txtSen.Text, txtSen.Text(i), ""))
lstOutput.Items.Add(txtZin.Text(i) & " occurs " & str & " time(s)")
End If
Next´
But i need it to be "m - 5" instead of repeating all the characters of "m"
Can you help me?
Take a look at this article. Does exactly what you are after. http://msdn.microsoft.com/en-us/library/bb397940.aspx
This is a method in vb.net that should help you aswell.
Public Function GetNumSubstringOccurrences(ByVal text As String, ByVal search As String) As Integer
Dim num As Integer = 0
Dim pos As Integer = 0
If Not String.IsNullOrEmpty(text) AndAlso Not String.IsNullOrEmpty(search) Then
While text.IndexOf(search.ToLower(), pos) > -1
num += 1
pos = text.ToLower().IndexOf(search.ToLower(), pos) + search.Length + 1
End While
End If
Return num
End Function
To loop the alphabet, do the following
Dim s As String = "ssssddfffccckkkllkeeiol"
For Each c In "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
Console.WriteLine(GetNumSubstringOccurrences(s, c))
Next

Generation of random string based on two characters in VB.NET

I'm trying to create a predefined number of rows, each having a predefined number of characters. The characters allowed are only 0's and 1's and are randomly generated.
I have achieved this with this code:
Dim _allowedChars As String = "01"
Dim randomNumber As New Random()
Dim chars As List(Of Char) = New List(Of Char)
Dim allowedCharCount As Integer = _allowedChars.Length
For o As Integer = 0 To rows - 1
For a As Integer = 0 To rowCharacters - 1
chars.Add(_allowedChars.Chars(CInt(Fix((_allowedChars.Length) * randomNumber.NextDouble()))))
Next a
For a As Integer = 0 To chars.Count - 1
'results for each row go here in a textbox line
Next a
chars = New List(Of Char)
'row o finished, new line and go for next row
Next o
This works great, an example output of setting 5 rows and 5 chars (only consisted of randomly generated 0's or 1's) is shown here:
11101
00000
11011
00000
01011
I now want to add an extra twist to it: specify the minimum percentage of 1's for each row, i.e. "even though randomly distributed, each row should have at least 20% of 1's". The percentage is based on the length of the chars in each row (variable rowCharacters in the code).
Anyone who could help me out on this one?
Thanks!
Dim _allowedChars As String = "01"
Dim randomNumber As New Random()
Dim chars As List(Of Char) = New List(Of Char)
Dim allowedCharCount As Integer = _allowedChars.Length
'
For o As Integer = 0 To rows - 1
Do
For a As Integer = 0 To rowCharacters - 1
chars.Add(_allowedChars.Chars(CInt(Fix((_allowedChars.Length) * randomNumber.NextDouble()))))
Next a
For a As Integer = 0 To chars.Count - 1
'results for each row go here in a textbox line
Next a
chars = New List(Of Char)
'row o finished, new line and go for next row
Loop Until IsValidPercent(chars, 20)
Next o
Function IsValidPercent(chars As List(Of Char), ReqPercentage as integer) as boolean
'
Dim counter as integer = 0
Dim qtyones as integer = 0
'
IsValidPercent = False
for counter = 0 to chars.count -1
if chars(counter) = "1" Then qtyones = qtyones + 1
next
if qtyones >= ((chars.count/100)*ReqPercentage) Then IsValidPercent = True
'
End Function

Find the length of a word in an array - Visual Basic

I have a richtextbox and I converted the words to an array, then I have code that will take the length and the output it... only problem is I don't know how to loop through all the different values of the array to check the length of each individual part of the array.
(I have this set on TextChanged)
Dim len1, len2, len3, len4, len5, len6, len7, len8, len9, len10, len11, len12, len13, len14, len15 As Integer
Dim input As String
Dim words As String()
Dim length As Integer
input = RichTextBox1.Text
words = input.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries)
For Each w In words
length = Len(w)
Select Case length
Case 1
len1 = len1 + 1
Case 2
len2 = len2 + 1
Case 3
len3 = len3 + 1
Case 4
len4 = len4 + 1
Case 5
len5 = len5 + 1
Case 6
len6 = len6 + 1
Case 7
len7 = len7 + 1
Case 8
len8 = len8 + 1
Case 9
len9 = len9 + 1
Case 10
len10 = len10 + 1
Case 11
len11 = len11 + 1
Case 12
len12 = len12 + 1
Case 13
len13 = len13 + 1
Case 14
len14 = len14 + 1
Case 15
len15 = len15 + 1
End Select
Next
letcount.onelet.Text = Val(len1)
letcount.twolet.Text = Val(len2)
letcount.threelet.Text = Val(len3)
letcount.fourlet.Text = Val(len4)
letcount.fivelet.Text = Val(len5)
letcount.sixlet.Text = Val(len6)
letcount.sevenlet.Text = Val(len7)
letcount.eightlet.Text = Val(len8)
letcount.ninelet.Text = Val(len9)
letcount.tenlet.Text = Val(len10)
letcount.elevenlet.Text = Val(len11)
letcount.twelevelet.Text = Val(len12)
letcount.thirteenlet.Text = Val(len13)
letcount.fourteenlet.Text = Val(len14)
letcount.fifteenlet.Text = Val(len15)
bendataclear showed you how to use a For Next loop. If you can use LINQ, you can use the following code:
Sub Main
Dim words As String() = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" }
Dim lengthsOnly = words.Select(Function(w) w.Length).ToArray()
Dim wordsAndLengths = words.Select(Function(w) New With { .Word = w, .Length = w.Length }).ToArray()
End Sub
The first Select gets only the word lengths, the second returns an array with each word and it's length.
David,
Some clarification for you:
w is a string. The compiler determines the type at design time. See this S.O. thread
What does VB.Net For Each Loop look at to Infer the Type
Dim words() As String = {"0", "1", "2"}
For Each w In words
System.Windows.Forms.MessageBox.Show(w)
Next
The type is inferred by the compiler by looking at the elements in the IEnumerable collection (array, list, etc.) The intellisense even knows it's a string at design time, even when w looks like it is defined as a generic. Try it yourself...
BUT. You can of course add the type explicitly
Dim words() As String = {"0", "1", "2"}
For Each w As String In words
System.Windows.Forms.MessageBox.Show(w)
Next
The string array example doesn't really demonstrate the convenience of the shorthand. See below
Dim dictionaryOfDictionaries As New Dictionary(Of String, Dictionary(Of String, String))
For Each d As KeyValuePair(Of String, Dictionary(Of String, String)) In dictionaryOfDictionaries
' do something with each dictionary d
Next
' is identical to
For Each d In dictionaryOfDictionaries
' do something with each dictionary d
Next
You can ignore double spaces and enters because they are considered empty:
'HOW CAN I EXCLUDE DOUBLE SPACES
'AND INCLUDE IF SOMEBODY PRESSES ENTER?
words = input.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries)
You could use another array?
Dim arr(14) as integer
Dim input As String
Dim words As String()
Dim length As Integer
input = RichTextBox1.Text
words = Split(input, " ")
For Each w in words
Dim l as Integer = Math.Min(Len(w) - 1,14)
arr(l) = arr(l) + 1
Next
Edit
In answer to questions in the comment:
w is a variable, and it is declared in the shortcut code For Each w in words
The shortcut declares a variable w then populates it with each member of the array words and runs the code between the For and next.
A longer way to do this without the shortcut would be something like:
Dim i as Integer
For i = 0 to words.GetUpperBound(0) -1
Dim w as string
w = words(i)
i = i + 1
'Rest of code
Next i
The next part Dim l as Integer = Math.Min(Len(w) - 1,14) sets l to the length of the word up to 14, as if we have a word longer than 15 letters it won't fit in the array.
Another way to do it would be:
Dim l as Integer
l = Len(w) - 1
If l > 14 then
l = 14
End If
arr(l) = arr(l) + 1