Number of occurrences in a string - vb6

I'm a total noob as far as visual basic goes.
In class I need to do the following: "Write a program that requests a sentence from the user and then records the number of times each letter of the alphabet occurs."
How would I go about counting the number of occurrences in the string?

Loop the chars and add to the list
Dim s As String = "tafata"
Dim count As New Dictionary(Of Char, Integer)()
For i As Integer = 0 To s.Length - 1
count(s(i)) = (If(count.ContainsKey(s(i)), count(s(i)) + 1, 1))
Next
Havent worked with linq that mutch, but i think you can try
Dim s As String = "tafata"
Dim t = From c In s _
Group c By c Into Group _
Select Group

As Dave said, the easiest solution would be to have an array of length 26 (for English), and loop through each character in the string, incrementing the correct array element. You can use the ASCII value of each character to identify which letter it is, then translate the ASCII number of the letter into the corresponding index number:
'Dimension array to 26 elements
Dim LetterCount(0 to 25) As Long
'Temporary index number
Dim tmpIdx As Long
'Temporary character
Dim tmpChar as String
'String to check
Dim checkStr As String
checkStr = "How many of each letter is in me?"
'Change all letters to lower case (since the upper case
'of each letter has a different ASCII value than its
'lower case)
checkStr = LCase(checkStr)
'Loop through each character
For n = 1 to Len(checkStr)
'Get current character
tmpChar = Mid(checkStr, n, 1)
'Is the character a letter?
If (Asc(tmpChar) >= Asc("a")) And (Asc(tmpChar) <= Asc("z")) Then
'Calcoolate index number from letter's ASCII number
tmpIdx = Asc(tmpChar) - Asc("a")
'Increase letter's count
LetterCount(tmpIdx) = LetterCount(tmpIdx) + 1
End If
Next n
'Now print results
For n = 0 to 25
Print Chr(Asc("a") + n) & " - " & CStr(LetterCount(n))
Next n

The quick and dirty way:
Public Function CountInStr(ByVal value As String, ByVal find As String, Optional compare As VbCompareMethod = VbCompareMethod.vbBinaryCompare) As Long
CountInStr = (LenB(value) - LenB(Replace(value, find, vbNullString, 1&, -1&, compare))) \ LenB(find)
End Function

I would count and remove every instance of the first character, and repeat until there are no characters left. Then display the count for each character detected. Much better than looping through once for every possible character, unless you know the possible range of characters is smaller than the length of the sentence.

Imports System.Linq
Dim CharCounts = From c In "The quick brown fox jumped over the lazy dog." _
Group c By c Into Count() _
Select c, Count

from itertools import groupby
sentence = raw_input("Your sentence:")
for char,group in groupby(sorted(sentence.lower())):
print(char+": "+`len(list(group))`)

Related

VB Control Naming by Variable

Dim LineNo as Integer
LineNo = CStr(channel) 'This can have a value of 1 to 100
If LineNo = 1 then
Text1.Text = "Line one selected"
Elseif LineNo = 2 then
Text2.Text = "Line one selected"
'Etc etc
End if
I need to replace the number "1" in Text1.Text and every other TextBox with the value of LineNo? For example:
Text{LineNo}.Text
So I would not have to do a repeated "If" and have a smaller one line code like this:
Text{LineNo}.Text = "Line " & LineNo & " selected"
How would I do this?
Look into a Control array of text boxes. You could have txtLine(), for example, indexed by the channel number.
LineNo = CStr(channel)
txtLine(channel).Text = "Line " & LineNo & " selected"
To create the array, set the Index property of each of the text boxes to an increasing integer, starting at 0.
If you have a finite and relatively small number, you can use a property. I've used this approach with up to 30+ elements in a pinch. Super simple, easy pattern to recognize and replicate in other places. A bit if a pain if the number of elements changes in the future, but extensible nevertheless.
It uses the Choose statement, which takes an index N and returns the Nth element (1-based), hence, the check makes sure that N is > 0 and <= MAX (which you would configure).
Public Property Get TextBox txt(ByVal N As Long)
Const MAX As Long = 10
If N <= 0 || N > MAX Then Exit Property ' Will return a "Nothing". You could return the bound element if you prefer
set txt = Choose(Text1, Text2, Text3, Text4, Text5, Text6, Text7, Text8, Text9, Text10)
End Property
Then, you can simply reference them with the Property, much like an alias:
txt(1).Text = "Line 1 text"
txt(2).Text = "Line 2 text"
If you have an arbitrary number, then you are likely using a control array already, which is simpler because it can be referenced by Index already, so you can directly reference it.
If neither of these work for you and you have a very large number of controls, you can scan the Controls collection in a similar Property, attempting to match ctrl.Name with the pattern of your choice (e.g., matching the first 4 characters to the string "Text", thus matching Text1, Text2, etc, for an unlimited number). Theoretically, this should be future-proofed, but that's just theoretical, because anything can happen. What it does do for you is to encapsulate the lookup in a way that "pretends" to be a control array. Same syntax, just you control the value.
Public Property Get TextBox txt(ByVal N As Long)
Dim I As Long
For I = 0 To Controls.Count - 1 ' Controls is zero-based
' Perform whatever check you need to. Obviously, if you have a "Label" named
' "Text38", the assignment will throw an error (`TextBox = Label` doesn't work).
If Left(Controls(I).Name, 4) = "Text" Then
set txt = Controls(I)
End If
Next
' If you want the Property to never return null, you could uncomment the following line (preventing dereference errors if you insist on the `.Text` for setting/getting the value):
' If txt Is Nothing Then Set txt = Text1
End Property
Use the same way as above: txt(n).Text = "..."

Random Characters added to String

I am trying to add a random set of numbers to the end of a string. I'm still learning the basics of VBS but this has really tricked me and I can't seem to find anything online.
I've tried:
string2 = "hello" + (Rnd() * Len(VALID_TEXT)) + 1
And:
x = rnd*10
string2 = "hello" + x
What am I doing wrong?
All random number generators rely on an underlying algorithm, usually fed by what’s called a seed number. You can use the Randomize statement to create a new seed number to ensure your random numbers don’t follow a predictable pattern.
To get the random numbers, using rnd alone is not sufficient as you will keep on getting the same random number again and again. You have to use randomize to achieve the task as shown below:
Dim strTest:strTest = "Hello"
Dim intNoOfDigitsToAppend:intNoOfDigitsToAppend = 5
Randomize
Msgbox "String before appending: " & strTest
strTest = fn_appendRandomNumbers(strTest,intNoOfDigitsToAppend)
Msgbox "String before appending: " & strTest
function fn_appendRandomNumbers(strToAppend,intNoOfRandomDigits)
Dim i
for i=1 to intNoOfRandomDigits
strToAppend= strToAppend & int(rnd*10) 'rnd gives a random number between 0 and 1, something like 0.8765341. Then, we multiply it by 10 so that the number comes in the range of 0 to 9. In this case, it becomes 8.765341. After that, we use the int method to truncate the decimal part so that we are only left with the Integer part. In this case, 765341 is truncated and we are left with only the integer 8
next
fn_appendRandomNumbers = strToAppend
end function
Reference 1
Reference 2
& is the string concatenation character. + is an old compatability concat character and will error if you mix text and numbers. Use + for maths only.

hidden space in excel

I tried almost all the methods (CLEAN,TRIM,SUBSTITUTE) trying to remove the character hiding in the beginning and the end of a text. In my case, I downloaded the bill of material report from oracle ERP and found that the item codes are a victim of hidden characters.
After so many findings, I was able to trace which character is hidden and found out that it's a question mark'?' (via VBA code in another thread) both at the front and the end. You can take this item code‭: ‭11301-21‬
If you paste the above into your excel and see its length =LEN(), you can understand my problem much better.
I need a good solution for this problem. Therefore please help!
Thank you very much in advance.
Thanks to Gary's Student, because his answer inspired me.
Also, I used this answer for this code.
This function will clean every single char of your data, so it should work for you. You need 2 functions: 1 to clean the Unicode chars, and other one to clean your item codes_
Public Function CLEAN_ITEM_CODE(ByRef ThisCell As Range) As String
If ThisCell.Count > 1 Or ThisCell.Count < 1 Then
CLEAN_ITEM_CODE = "Only single cells allowed"
Exit Function
End If
Dim ZZ As Byte
For ZZ = 1 To Len(ThisCell.Value) Step 1
CLEAN_ITEM_CODE = CLEAN_ITEM_CODE & GetStrippedText(Mid(ThisCell.Value, ZZ, 1))
Next ZZ
End Function
Private Function GetStrippedText(txt As String) As String
If txt = "–" Then
GetStrippedText = "–"
Else
Dim regEx As Object
Set regEx = CreateObject("vbscript.regexp")
regEx.Pattern = "[^\u0000-\u007F]"
GetStrippedText = regEx.Replace(txt, "")
End If
End Function
And this is what i get using it as formula in Excel. Note the difference in the Len of strings:
Hope this helps
You have characters that look like a space character, but are not. They are UniCode 8236 & 8237.
Just replace them with a space character (ASCII 32).
EDIT#1:
Based on the string in your post, the following VBA macro will replace UniCode characters 8236 amd 8237 with simple space characters:
Sub Kleanup()
Dim N1 As Long, N2 As Long
Dim Bad1 As String, Bad2 As String
N1 = 8237
Bad1 = ChrW(N1)
N2 = 8236
Bad2 = ChrW(N2)
Cells.Replace what:=Bad1, replacement:=" ", lookat:=xlPart
Cells.Replace what:=Bad2, replacement:=" ", lookat:=xlPart
End Sub

How to fetch text from dynamically changing string

Every day I am receiving values as given below, since to automate I want fetch last part of the string from a text. For example, from the following
a) 999999000045090
b) 9990090105
c) 9999010000
d) 990000660000
from the above I need to fetch actual values in the right as given here
a) 45090
b) 90105
c) 10000
d) 660000
since the length is varying and not fixed I need help to resolve
You can use a regular expression:
Dim inputString, regularExpression, outputString
inputString = "999999000045090"
Set regularExpression = New Regexp
regularExpression.Pattern = "^9+0+"
outputString = regularExpression.Replace(inputString, "")
^ will match the start of the string, 9+ will match 1 or more nines and 0+ will match 1 or more zeroes.
Which means that, in this example, 9999990000 will be replaced by an empty string, and that outputString will be 45090.
Disclaimer: not tested. I am not familiar with VBScript.

Match the words present in a string. If a words repeats in the sentence them give a message "Match", else give a message "No match"

I'm tyring to make program which takes a sentence as input and then splits the different words in it. Now it compares the words and if a word repeats then gives a message match otherwise it gives no match. But on executing the same no MsgBox is displayed.
This is the script that I have written:
Dim sent
Dim i
Dim j
Dim k
sent = "Its a good day but every day is a good day"
words = Array(Split(sent))
For i = LBound(words) To UBound(words)-1
For j = LBound(words)+1 To UBound(words)
k = StrComp(words(i), words(j))
If k=0 Then
MsgBox ("Match")
Else
MsgBox ("No Match")
End If
Next
Next
The For loop will never run because the UBound(words) will return 0.
This is because the Split() function returns an Array so there is no need for the extra Array() call which ends up giving you a single element Array containing another Array.
The solution is to change
words = Array(Split(sent))
to
words = Split(sent)
That will fix your initial problem, but there are other issues with the code you will need to address before it works correctly.
VBScript's tool for classifying/counting tokens of types/recognizing is the Dictionary.
Demo:
Option Explicit
Dim a : a = Split("Its a good day but every day is a good day")
Dim d : Set d = CreateObject("Scripting.Dictionary")
Dim w
For Each w In a
d(w) = d(w) + 1
If 1 < d(w) Then
WScript.Echo "more than one " & w & " - could 'Exit For'"
End If
Next
For Each w In d.Keys()
WScript.Echo w, d(w)
Next
(look ma, no nested loops!)
output:
cscript 42004404.vbs
more than one day - could 'Exit For'
more than one a - could 'Exit For'
more than one good - could 'Exit For'
more than one day - could 'Exit For'
Its 1
a 2
good 2
day 3
but 1
every 1
is 1

Resources