View Single Post
  #11   Report Post  
Posted to microsoft.public.excel.programming
Peter T Peter T is offline
external usenet poster
 
Posts: 5,600
Default Get First Letter of each word

"Ron Rosenfeld" wrote in message
...
On Wed, 20 Feb 2008 12:04:03 -0500, "Rick Rothstein \(MVP - VB\)"
wrote:

Function IDa(str As String) As String
Dim sTemp() As String
Dim i As Long
sTemp = Split(str)

For i = 0 To UBound(sTemp)
If UCase(sTemp(i)) Like "[A-Z]*" Then
IDa = IDa & UCase(Left(sTemp(i), 1))
End If
Next i

End Function


Just a point of information... using the UCase function in the If-Then
statement above (to parse upper and lower case letters) will work as

shown,
but this should be more efficient:

If sTemp(i) Like "[a-zA-Z]*" Then

Rick


Well, I wondered about checking that. So I ran a routine identical except

for
the comparison statement (see code below).

For 10,000 repetitions, the UCase variation took 0.4375 seconds, whereas

the
[a-zA-Z] variant took 1.125 seconds. So it would appear the UCase is the

more
"efficient".

=================================
Option Explicit

Sub test()
Const Str As String = "Rehau - w/Shield Cvr & Package "
Dim sTemp() As String
sTemp = Split(Str)
Dim IDa As String
Dim dTimer As Double
Dim i As Long
Dim j As Long
Const lReps As Long = 10000

dTimer = Timer
For j = 1 To lReps
For i = 0 To UBound(sTemp)
If UCase(sTemp(i)) Like "[A-Z]*" Then
IDa = IDa & UCase(Left(sTemp(i), 1))
End If
Next i
Next j

Debug.Print Timer - dTimer

dTimer = Timer
For j = 1 To lReps
For i = 0 To UBound(sTemp)
If sTemp(i) Like "[a-zA-Z]*" Then
IDa = IDa & UCase(Left(sTemp(i), 1))
End If
Next i
Next j

Debug.Print Timer - dTimer

End Sub
===========================
0.4375
1.125
=========================

--ron


Hi Ron,

I don't think those comparative tests are quite right.
Len(IDa) increases from 0-40000 in the first test, and continues up to 80000
in the second. Try reversing the order of the tests and the timings are
reversed (roughly)

If I reset IDa at the start of each loop -
For j = 1 To lReps
IDa = ""

I find both timings improve significantly with Like "[a-zA-Z]*" about twice
as quick as Ucase.

However if I comment this line
' IDa = IDa & UCase(Left(sTemp(i), 1))
the relative difference is much greater still in favour of Like "[a-zA-Z]*"
vs UCase

Regards,
Peter T