|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| ||||||||||||||||||||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Count common characters in two strings
is there any function in Visual Basic 2008 that returns the number of common characters in two strings.
for example: string 1: "abcdef" string 2: "abc" the function should return 3. |
|
#2
|
||||
|
||||
|
Be more specific. Are the common characters just at the beginning of the string, or can they be scattered throughout?
What should the function return when given "abcdefg" and "abcefdg"? |
|
#3
|
|||
|
|||
|
scatterd...
shuld return 7 in ur case. Quote:
|
|
#4
|
|||
|
|||
|
Something like:
Code:
For i = 1 to len(str1)
c = mid(str1,i,1)
if instr(str2, c) then
count = count + 1
end if
Next
You may need to verify the syntax of the functions, I don't do much vb these days.
__________________
====== Doug G ====== I didn't attend the funeral, but I sent a nice letter saying I approved of it. --Mark Twain |
|
#5
|
||||
|
||||
|
Done in Access 2k3 it should work in VB2008 but may need something ... anyway the concept is solid
Code:
' // Will count unique letters in the string
' || Will *not* count numbers or other characters
Function UniqueLetters(strInput As String) As Integer
Dim HasLetter(0 To 25) As Boolean ' A flag for each of the 26 letters of the alphabet
Dim n As Integer ' A loop counter
Dim c As Integer ' To get the letter
' // Loop through the string and flag each letter
For n = 1 To Len(strInput)
' // Get the ASCII value then convert to 0(A)-25(Z)
' || Convert to upper case count A and a only as 1
c = Asc(Mid(UCase(strInput), n, 1)) - 65
' // If it's a letter record that letter as counted
If c >= 0 And c <= 25 Then
HasLetter(c) = True
End If
Next n
' // Count the letters used and return result
For n = 0 To 25
If HasLetter(n) Then
UniqueLetters = UniqueLetters + 1
End If
Next n
End Function
Sub Examples()
Dim strPass As String
strPass = "303 Lee Street" ' note it won't count the space or numbers
MsgBox strPass & " has " & UniqueLetters(strPass) & " unique letters"
strPass = "The Quick Brown Fox Jumped Over The Lazy Dogs"
MsgBox strPass & " has " & UniqueLetters(strPass) & " unique letters"
strPass = "equinox"
MsgBox strPass & " has " & UniqueLetters(strPass) & " unique letters"
End Sub
__________________
medialint.com "Beware of the man who works hard to learn something, learns it, and finds himself no wiser than before. He is full of murderous resentment of people who are ignorant without having come by their ignorance the hard way." - Vonnegut - Cat's Cradle, 1963 |
![]() |
| Viewing: Dev Shed Forums > Programming Languages - More > Visual Basic Programming > Count common characters in two strings |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|