vb6 split space delimited string at every nth space - vb6

I have a space delimited string variable. I would like to store the contents of the variable into an array. Using split, I can store every space delimited value in an array. I would prefer if I could separate the string variable at every 7th space. For example, the text could read:
"hello hello hello hello hello hello hello hi hi hi hi hi hi hi hey hey hey hey hey hey hey"
This isn't the actual content of the string, but a simpler version that is easier to read. I want to separate at the places where the words change, or every 7th space. Any help would be greatly appreciated. My current code looks like this, which splits at every space.
ReDim StatsArray(ArrInc)
StatsArray = Split(Stats)
For i = 0 To UBound(StatsArray())
If i > UBound(StatsArray()) Then
ReDim Preserve StatsArray(i + ArrInc)
End If
' MsgBox StatsArray(i) ' When not commented out, this help me check the array
Next

There isn't any built-in function that will do this for you. A couple of solutions come to mind: (1) Do your split, then iterate your array. Concatenate seven array elements in a string variable. Write the result to a new array. Rinse and repeat. (2) Create an Array. Iterate through the string character by character, pushing each character into a variable and keeping track of the spaces you encounter; when you reach the seventh space add an element to your array, copy the variable to it, and clear the variable. Rinse and repeat.
The first one strikes me as a bit faster, but I could be quite wrong about that.

If I understand what you're trying to do, a string of "1234 12345678 123" would get split into 1234, 1234567, 8, 123. Is this correct?
If so, then you can use Regular Expressions to do the split for you.
Function Split7(S As String)
Dim regex As New RegExp
regex.Pattern = "[^ ]{7}"
regex.Global = True
Split7 = Split(regex.Replace(S, "$& "), " ")
End Function
This will insert a space after every 7th character that is not a space. Then use the split function to get the whole thing into an array.

Another stab at it, though I'd probably optimize the ReDim Preserves, doing them in chunks:
Option Explicit
Private Function SplitN( _
ByRef Source As String, _
ByVal Delim As String, _
ByVal N As Long) As String()
'Delim can be multi-character.
'Always returns at least 1-element result,
'even if Source = "".
Dim SearchPos As Long
Dim PartPos As Long
Dim DelimPos As Long
Dim Parts() As String
Dim DelimCount As Long
Dim PartsCount As Long
SearchPos = 1
PartPos = SearchPos
Do
DelimPos = InStr(SearchPos, Source, Delim)
If DelimPos > 0 Then
DelimCount = DelimCount + 1
If DelimCount = N Then
DelimCount = 0
ReDim Preserve Parts(PartsCount)
Parts(PartsCount) = _
Mid$(Source, PartPos, DelimPos - PartPos)
PartsCount = PartsCount + 1
PartPos = DelimPos + Len(Delim)
End If
SearchPos = DelimPos + Len(Delim)
End If
Loop While DelimPos > 0
ReDim Preserve Parts(PartsCount)
Parts(PartsCount) = Mid$(Source, PartPos)
SplitN = Parts
End Function
Private Sub Form_Load()
Dim S As String
Dim Parts() As String
Dim P As Long
S = "hello hello hello hello hello hello hello " _
& "hi hi hi hi hi hi hi " _
& "hey hey hey hey hey hey hey"
Text1.SelStart = 0
Text1.SelText = S & vbNewLine & vbNewLine
Parts = SplitN(S, " ", 7)
Text1.SelText = "Ubound() = " & UBound(Parts) & vbNewLine
For P = 0 To UBound(Parts)
Text1.SelText = Parts(P) & vbNewLine
Next
End Sub

Related

Randomly rearrange letters in a word

Using this SO question / answer as a starting point: Splitting a single word into an array of the consituent letters
I have this simple bit of code to take a word and split the word into single letters:
<%
Dim word1, i
word1 = "particle"
For i = 1 To Len(word1)
Response.Write "<p>" & Mid(word1, i, 1) & "</p>"
Next
%>
I would like to know how to take a word (variable length, rather than a word that is 8 characters long as in the example above), and randomly rearrange the letters of the word - so that e.g. particle could be e.g.:
alpreict
lircpaet
ctelaipr
teapclir
raeitclp
This is an example of what I'd like to achieve: https://onlinerandomtools.com/shuffle-letters
However, I realise that is easier said than done.
I wondered if anyone has any advice about how it might be possible to achieve this using Classic ASP please?
Thanks
Here's one way to do it:
Function ShuffleText(p_sText)
Dim iLength
Dim iIndex
Dim iCounter
Dim sLetter
Dim sText
Dim sShuffledText
' Copy text passed as parameter
sText = p_sText
' Get text length
iLength = Len(sText)
For iCounter = iLength To 1 Step -1
' Get random index
iIndex = 1 + Int(Rnd * (iCounter))
' Get character at that index
sLetter = Mid(sText, iIndex, 1)
' Remove character from string
sText = Left(sText, iIndex - 1) & Mid(sText, iIndex + 1)
' Add character to shuffled string
sShuffledText = sShuffledText & sLetter
Next
' Return shuffled text
ShuffleText = sShuffledText
End Function
This code selects a random character in the string, removes it and adds it to a shuffled string. It repeats this process until it has gone through all characters.
There are probably more efficient ways to do this by randomizing an array of numbers first and using those numbers as iIndex, without manipulating the sText string.

How capitalize fullname in vb6

hi all i have this question as bellow
how capitalize full in one vb6 Vb6 string variable
‘example
‘my fullname
Dim fullname as string
Fullname = “abdirahman abdirisaq ali”
Msgbox capitalize(fullname)
it prints abdirahmanAbdirisaq ali that means it skips the middle name space even if I add more spaces its same .
this is my own code and efforts it takes me at least 2 hours and still .
I tired it tired tired please save me thanks more.
Please check my code and help me what is type of mistakes I wrote .
This is my code
Private Function capitalize(txt As String) As String
txt = LTrim(txt)
temp_str = ""
Start_From = 1
spacing = 0
For i = 1 To Len(txt)
If i = 1 Then
temp_str = UCase(Left(txt, i))
Else
Start_From = Start_From + 1
If Mid(txt, i, 1) = " " Then
Start_From = i
spacing = spacing + 1
temp_str = temp_str & UCase(Mid(txt, Start_From + 1, 1))
Start_From = Start_From + 1
Else
temp_str = temp_str & LCase(Mid(txt, Start_From, 1))
End If
End If
Next i
checkName = temp_str
End Function
It's far simpler than that. In VB6 you should use Option Explicit to properly type your variables. That also requires you to declare them.
Option Explicit
Private Function capitalize(txt As String) As String
Dim temp_str as String
Dim Names As Variant
Dim Index As Long
'Remove leading and trailing spaces
temp_str = Trim$(txt)
'Remove any duplicate spaces just to be sure.
Do While Instr(temp_str, " ") > 0
temp_str = Replace(temp_str, " ", " ")
Loop
'Create an array of the individual names, separating them by the space delimiter
Names = Split(temp_str, " ")
'Now put them, back together with capitalisation
temp_str = vbnullstring
For Index = 0 to Ubound(Names)
temp_str = temp_str + Ucase$(Left$(Names(Index),1)) + Mid$(Names(Index),2) + " "
Next
'Remove trailing space
capitalize = Left$(temp_str, Len(temp_str) - 1)
End Function
That's the fairly easy part. If you are only going to handle people's names it still needs more work to handle names like MacFarland, O'Connor, etc.
Business names get more complicated with since they can have a name like "Village on the Lake Apartments" where some words are not capitalized. It's a legal business name so the capitalization is important.
Professional and business suffixes can also be problematic if everything is in lower case - like phd should be PhD, llc should be LLC, and iii, as in John Smith III, would come out Iii.
There is also a VB6 function that will capitalize the first letter of each word. It is StrConv(string,vbProperCase) but it also sets everything that is not the first letter to lower case. So PhD becomes Phd and III becomes Iii. Where as the above code does not change the trailing portion to lower case so if it is entered correctly it remains correct.
Try this
Option Explicit
Private Sub Form_Load()
MsgBox capitalize("abdirahman abdirisaq ali")
MsgBox capitalize("abdirahman abdirisaq ali")
End Sub
Private Function capitalize(txt As String) As String
Dim Names() As String
Dim NewNames() As String
Dim i As Integer
Dim j As Integer
Names = Split(txt, " ")
j = 0
For i = 0 To UBound(Names)
If Names(i) <> "" Then
Mid(Names(i), 1, 1) = UCase(Left(Names(i), 1))
ReDim Preserve NewNames(j)
NewNames(j) = Names(i)
j = j + 1
End If
Next
capitalize = Join(NewNames, " ")
End Function
Use the VB6 statement
Names = StrConv(Names, vbProperCase)
it's all you need (use your own variable instead of Names)

How to display length of word count in vb?

So I've been trying for hours to figure out how to display the length of word count in vb.
For example, if I type in a sentence in a rich textbox and I click a button, I want a form to show up listing the number of one-letter words, two-letter words, three-letter words and so on within that sentence. The number of words of specific length will be outputted in labels, of course.
I found this short code online for word count:
dim wordcount as integer
dim a as string() = RichText.Text.Split(" ")
wordcount = a.length
However, I'm not sure if this code can be used to get the length of word count. Any ideas of how I can achieve outputting the number of words of a specific length in a label? Thank you.
What about something like:
Private Sub mnuCount_Click()
Const DELIMITERS As String = vbNewLine & " !"",.:;?"
Dim WordCounts(1 To 100) As Long
Dim Msg As String
Dim I As Integer
Dim WordCount As Long
With RTB
.Visible = False
.SelStart = 0
Do
.UpTo DELIMITERS, vNegate:=True
.Span DELIMITERS, vNegate:=True
If .SelLength > 0 Then
WordCounts(.SelLength) = WordCounts(.SelLength) + 1
.SelStart = .SelStart + .SelLength
Else
Exit Do
End If
Loop
.SelStart = 0
.Visible = True
End With
Msg = "Length" & vbTab & "Count"
For I = 1 To 100
If WordCounts(I) > 0 Then
Msg = Msg & vbNewLine _
& CStr(I) & vbTab & CStr(WordCounts(I))
WordCount = WordCount + WordCounts(I)
End If
Next
Msg = Msg & vbNewLine _
& "Grand total:" & vbNewLine _
& vbTab & CStr(WordCount)
MsgBox Msg
End Sub
Pradnya's code, translated to VB6:
Option Explicit
Private Sub Command1_Click()
Dim str As String
Dim splitStr() As String
Dim i As Integer
str = "ABC DEF GHIJ KLMNOPQ"
splitStr = Split(str, " ")
MsgBox "Number of words = " & UBound(splitStr) + 1 & vbCrLf & _
"Average Length = " & Len(Replace(str, " ", "")) / (UBound(splitStr) + 1)
End Sub
I made a few simplifications as well. There's no need to go through the loop to get the average. All you have to do to get the length of the whole is remove the spaces and divide by the number of elements in the array.
However, if you want to get a count of the number of words of each length, you'll have to loop through the array, getting the length of each word and storing those values one by one. Best way to do that is to set a reference to scrrun.dll (Windows Scripting Runtime) and use a Dictionary object to store the values.

i want to know the times of occurrance one word in the text-box in VB 0.6

want to know the count of occurrence one word in the text box in Visual BASIC v.0.6 ?
i tried to use the counter from the list but it was not good
for example: in the following sentence:
" go to play and go to home"... the verb "go" appear 2 times ..then.. i want the code that count the number of occurrence of verb "go" and say to me through label for example: 2 times
for example: in the following sentence:
" go to play and go to home"... the verb "go" appear 2 times ..then.. i want the code that count the number of occurrence of verb "go" and say to me through label for example: 2 times
You can use replace() to remove the word from the string, and then compare the length resulting string with the length of the original string, and devide that by the length of the word
Option Explicit
Private Sub Command1_Click()
Label1.Caption = CStr(CountWord(Text1.Text, "go")) & " times"
End Sub
Private Sub Form_Load()
Text1.Text = " go to play and go to home"
End Sub
Private Function CountWord(strText As String, strWord As String) As Long
CountWord = (Len(strText) - Len(Replace(strText, strWord, ""))) / Len(strWord)
End Function
the function CountWord above finds the amount of strWord in strText, it doesn't search for separate words, but also adds one to the count if strWord is part of a larger word
For example " go to play and go to home to search on google" would count 3 instances of "go"
Try the following code: -
Dim txt$, find$, i1%, count%
txt = "go to play and go to home"
find = "go"
i1 = 0
Do
i1 = InStr(i1 + 1, txt, find)
If i1 > 0 Then
count = count + 1
i1 = i1 + Len(find)
Else
Exit Do
End If
Loop
MsgBox count
You can use regular expressions to count word occurrences
Private Sub Form_Load()
Debug.Print CountWords(" go to play and G.O to home to search on g.o" & vbCrLf & "ogle", "g.o")
End Sub
Private Function CountWords(sText As String, sWord As String) As Long
Dim sPattern As String
sPattern = pvInitRegExp("[-[\]{}()*+?.,\\^$|#\s]").Replace(sWord, "\$&")
CountWords = pvInitRegExp("\s" & sPattern & "\s").Execute(sText).Count
End Function
Private Function pvInitRegExp(sPattern As String) As Object
Set pvInitRegExp = CreateObject("VBScript.RegExp")
With pvInitRegExp
.Pattern = sPattern
.Global = True
.IgnoreCase = True
.MultiLine = True
End With
End Function
This takes care of word boundaries too so "google" is not counted.

How to Remove Specific Special Characters

I have a string like X5BC8373XXX. Where X = a special character equals a Square.
I also have some special characters like \n but I remove them, but I can't remove the squares...
I'd like to know how to remove it.
I Found this method:
Dim Test As String
Test = Replace(Mscomm1.Input, Chr(160), Chr(64) 'Here I remove some of the special characters like \n
Test = Left$(Test, Len(Test) -2)
Test = Right$(Test, Len(Test) -2)
This method DOES remove those special characters, but it's also removing my first character 5.
I realize that this method just remove 2 characters from the left and the right,
but how could I work around this to remove these special characters ?
Also I saw something with vblF, CtrlF something like this, but I couldn't work with this ;\
You can use regular expressions. If you want to remove everything that's not a number or letter, you can use the code below. If there are other characters you want to keep, regular expressions are highly customizable, but can get a little confusing.
This also has the benefit of doing the whole string at once, instead of character by character.
You'll need to reference Microsoft VBScript Regular Expressions in your project.
Function AlphaNum(OldString As String)
Dim RE As New RegExp
RE.Pattern = "[^A-Za-z0-9]"
RE.Global = True
AlphaNum = RE.Replace(OldString, "")
End Function
Cleaning out non-printable characters is easy enough. One brute-force but easily customizable method might be:
Private Function Printable(ByVal Text As String) As String
Dim I As Long
Dim Char As String
Dim Count As Long
Printable = Text 'Allocate space, same width as original.
For I = 1 To Len(Text)
Char = Mid$(Text, I, 1)
If Char Like "[ -~]" Then
'Char was in the range " " through "~" so keep it.
Count = Count + 1
Mid$(Printable, Count, 1) = Char
End If
Next
Printable = Left$(Printable, Count)
End Function
Private Sub Test()
Dim S As String
S = vbVerticalTab & "ABC" & vbFormFeed & vbBack
Text1.Text = S 'Shows "boxes" or "?" depending on the font.
Text2.Text = Printable(S)
End Sub
This will remove control characters (below CHR(32))
Function CleanString(strBefore As String) As String
CleanString = ""
Dim strAfter As String
Dim intAscii As Integer
Dim strTest As String
Dim dblX As Double
Dim dblLen As Double
intLen = Len(strBefore)
For dblX = 1 To dblLen
strTest = Mid(strBefore, dblX, 1)
If Asc(strTest) < 32 Then
strTest = " "
End If
strAfter = strAfter & strTest
Next dblX
CleanString = strAfter
End Function

Resources