Results 1 to 27 of 27

Thread: Find the Last letter in a string containing letters and numbers

  1. #1

    Thread Starter
    New Member
    Join Date
    Jun 2005
    Posts
    11

    Find the Last letter in a string containing letters and numbers

    HI

    I am trying to find the last letter within a string.

    I have a field which contains data like CV8 7TY0124 121212

    I am trying to extract everything prior to the first letter, ie CV8 7TY

    I am thinking about finding the last letter within a string, then using the right, left or Mid funtion to grab the characters I want. Am I on the right lines?

    Would appreciate any help

  2. #2
    Hyperactive Member g4hsean's Avatar
    Join Date
    May 2006
    Posts
    267

    Lightbulb Re: Find the Last letter in a string containing letters and numbers

    Ok it seem's to me like its a zip code if so you could mid$ (string,1,7). But if you want the rest after the last letter being
    example string = CV8 7TY
    Last letter = Y<---------------------------

    then what you do is you Mid$(String,7,Len(string)) but that's only if you want letters or numbers after the CV8 7TY. Please tell me if that's what you wanted because your post is not exactly clear.

    P.S Hope i helped you
    Coding's a Breeze if you'r at ease! GOD THATS CORNY!!
    -

  3. #3
    Fanatic Member schoolbusdriver's Avatar
    Join Date
    Jan 2006
    Location
    O'er yonder
    Posts
    1,020

    Re: Find the Last letter in a string containing letters and numbers

    I am trying to extract everything prior to the first letter, ie CV8 7TY
    I assume you mean "prior to the last letter"

    It would be faster using InstrRev and checking for the first character which isn't a space or number (Val) then using Left. (assuming you don't want to return a fixed length string. Is it a car number plate?)
    Last edited by schoolbusdriver; Jun 2nd, 2006 at 05:21 AM.

  4. #4
    Junior Member purplegerbil's Avatar
    Join Date
    May 2006
    Location
    Bradford, Yorkshire, UK
    Posts
    23

    Re: Find the Last letter in a string containing letters and numbers

    This code will search through a given string looking for a letter. if found the string will be split into two halves.

    I used, 1 text, 1 command and 2 labels.

    VB Code:
    1. Option Explicit
    2.  
    3. Private Sub Command1_Click()
    4.  
    5.     Dim inString As String      ' Input string
    6.     Dim leftString As String
    7.     Dim rightString As String
    8.     Dim pos As Integer          ' Position within input string
    9.     Dim found As Boolean        ' if found character flag
    10.     Dim tmpChar As String       ' single character within string
    11.    
    12.     inString = Text1.Text       ' get info from text box
    13.     found = False               ' set flag
    14.     pos = Len(inString)         ' get start position, last character in string
    15.    
    16.    
    17.     ' Loop through string checking each character
    18.     Do
    19.         tmpChar = Mid$(UCase(inString), pos, 1) ' get character
    20.        
    21.         ' check if a letter, if so, change flag to true
    22.         If Asc(tmpChar) >= 65 And Asc(tmpChar) <= 90 Then found = True
    23.    
    24.         ' move to next character
    25.         pos = pos - 1
    26.     Loop Until found = True Or pos = 0
    27.    
    28.     If found = True Then pos = pos + 1
    29.        
    30.     leftString = Left$(inString, pos)
    31.     rightString = Right$(inString, Len(inString) - pos)
    32.    
    33.     ' output to user
    34.     Label1 = leftString
    35.     Label2 = rightString
    36.    
    37.  
    38. End Sub

    Hope this helps.

    pG

  5. #5
    Hyperactive Member g4hsean's Avatar
    Join Date
    May 2006
    Posts
    267

    Thumbs up Re: Find the Last letter in a string containing letters and numbers

    Yea anyway's good hope its what the persone want's and i forgot to add the string reverse.
    Coding's a Breeze if you'r at ease! GOD THATS CORNY!!
    -

  6. #6
    Fanatic Member schoolbusdriver's Avatar
    Join Date
    Jan 2006
    Location
    O'er yonder
    Posts
    1,020

    Re: Find the Last letter in a string containing letters and numbers

    I forgot something too, g4hsean. Checking zero with val. The search will probably have to test for "0" too!
    Last edited by schoolbusdriver; Jun 2nd, 2006 at 04:56 PM.

  7. #7
    PowerPoster
    Join Date
    May 2006
    Location
    Location, location!
    Posts
    2,673

    Re: Find the Last letter in a string containing letters and numbers

    Quote Originally Posted by schoolbusdriver
    Is it a car number plate?
    It's a UK postcode (US equivalent is zipcode) and phone number

  8. #8
    Oi, fat-rag! bushmobile's Avatar
    Join Date
    Mar 2004
    Location
    on the poop deck
    Posts
    5,592

    Re: Find the Last letter in a string containing letters and numbers

    A For Next loop would probably be more appropriate in this situation:
    VB Code:
    1. Private Function Extract(ByVal sText As String) As String
    2.     Dim N As Long
    3.     If Len(sText) = 0 Then Exit Function
    4.    
    5.     For N = Len(sText) To 1 Step -1
    6.         Select Case Mid$(sText, N, 1)
    7.             Case "a" To "z", "A" To "Z"
    8.                 Exit For
    9.         End Select
    10.     Next N
    11.     Extract = Left$(sText, N)
    12.     ' To get the right half of the string do:
    13.     ' Mid$(sText, N + 1)
    14. End Function

  9. #9
    Hyperactive Member g4hsean's Avatar
    Join Date
    May 2006
    Posts
    267

    Thumbs up Re: Find the Last letter in a string containing letters and numbers

    I believe bushmobile has the best responce to your question.
    Coding's a Breeze if you'r at ease! GOD THATS CORNY!!
    -

  10. #10
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Find the Last letter in a string containing letters and numbers

    Here's a one liner if you are sure the last character won't be a "0" (zero), otherwise modify appropriately:
    VB Code:
    1. Function ExtractLastNum(ByVal sIn As String) as String
    2.     ExtractLastNum = StrReverse(Val(StrReverse(sIn)))
    3. End Function
    4.  
    5. Private Sub Command1_Click()
    6.     ''usage
    7.     MsgBox ExtractLastNum("CV8 7TY0124 121212")
    8. End Sub
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  11. #11
    Fanatic Member
    Join Date
    Jan 2005
    Location
    In front of this pc.
    Posts
    580

    Re: Find the Last letter in a string containing letters and numbers

    If I wanted to parse a string looking for the last number, or letter I'd probably go with a regular expression. RegExps can be more system intensive than other string parsing but they are also more powerfull.

    If you wanted to use this approach you would start by adding a reference to MS VBScript Regular Expressions 5.5 and then try this (untested off the top of my head) code:

    VB Code:
    1. Dim Reg as New Regular Expression
    2. Dim m as Match
    3. Reg.IgnoreCase
    4. Reg.pattern = "^(.*[a-z])[^a-z]"
    5. for Each m in Reg.Execute(testString)
    6.      ' m.submatches(0) should be the the string through the last letter
    7. next m

    If you want to return only the last letter move the parenthesis in the pattern so that the pattern would be "^.*([a-z])[^a-z]"

    So you'll understand that a little the reg pattern can be interpeted as saying:

    From the start of the string take any number of characters of any type (.*) until a letter is found ([a-z]) which is follwed by anything other than another letter ([^a-z]).

    If you want to make it case sensetive remove the ignorecase command and use the appropiately cased a-z. You can even mix and match by using stuff like "[a-zB]" which would match all lower case letters and a uppercase B, etc.

    While I'm here, if you are reading files and wan't to parse them a line a time add a "$" to the end of the pattern as the $ is interpetted as "end of line"
    What bug? That's not a bug. It's an undocumented feature!

  12. #12
    Oi, fat-rag! bushmobile's Avatar
    Join Date
    Mar 2004
    Location
    on the poop deck
    Posts
    5,592

    Re: Find the Last letter in a string containing letters and numbers

    Quote Originally Posted by anotherVBnewbie
    RegExps can be more system intensive than other string parsing but they are also more powerfull.
    They maybe more powerful, but how much power is really needed in a situation like this. It's kinda like trying to hammer a nail with a steamroller - it's just going to slow you down.

    Attached is a speed test comparing my code with the RegExp one - whilst they performed equally in the IDE, once compiled the 'built-in' code was 40% faster than the RegExp stuff.

    RegExp can be very useful but, for simple things like this, the standard function calls are often faster and of course don't require any overhead.

    Attached Files Attached Files

  13. #13
    Fanatic Member schoolbusdriver's Avatar
    Join Date
    Jan 2006
    Location
    O'er yonder
    Posts
    1,020

    Re: Find the Last letter in a string containing letters and numbers

    Bush's code still looks best. It's flexible too. Throw a Split in there and you can display the postcode by the phone number. Ideal for telesales...

  14. #14
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Find the Last letter in a string containing letters and numbers

    I agree with Bushmobile - using a FOR loop and stepping backwards through the string is an age-old standard algorithm for doing something like this.

    If you were coding it in ASM you would do exactly the same thing.

    I would have checked for 0 through 9 and space myself - but then you never indicated what would happen if a non-letter/non-numeric character was in place - such as a # or @ sign.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  15. #15
    Oi, fat-rag! bushmobile's Avatar
    Join Date
    Mar 2004
    Location
    on the poop deck
    Posts
    5,592

    Re: Find the Last letter in a string containing letters and numbers

    Quote Originally Posted by szlamany
    I would have checked for 0 through 9 and space myself - but then you never indicated what would happen if a non-letter/non-numeric character was in place - such as a # or @ sign.
    That's the reason i chose to check for letters

    but 0-9 & space would be quicker - also you'd use a byte array if you were looking for more speed

  16. #16
    Fanatic Member schoolbusdriver's Avatar
    Join Date
    Jan 2006
    Location
    O'er yonder
    Posts
    1,020

    Re: Find the Last letter in a string containing letters and numbers

    At 2Ghz+, bush, who cares! Easily understood + flexible. Nice.

  17. #17
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Find the Last letter in a string containing letters and numbers

    Quote Originally Posted by schoolbusdriver
    At 2Ghz+, bush, who cares! Easily understood + flexible. Nice.
    Although faster chips are great - speed of CPU is not keeping up with requirement for speed on the part of the user.

    Everytime you learn an algorithm, technique or construct and appreciate why it's this-or-that, fast-or-slow, memory-hog-or-not - that makes you a better programmer in the long run.

    I've been doing this for a very long time - back to when your program had to fit in 16K of memory.

    Every incremental step that CPU, memory and disk size took in the past 20 years was accompanied by a user-thirst for power and speed that surpassed what was just delivered.

    Sorry for the rant - but this thread seemed to be all about different ways to attack a simple problem

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  18. #18
    PowerPoster
    Join Date
    May 2006
    Location
    Location, location!
    Posts
    2,673

    Re: Find the Last letter in a string containing letters and numbers

    Quote Originally Posted by szlamany
    Sorry for the rant - but this thread seemed to be all about different ways to attack a simple problem
    No, don't apologise, you're right to rant...just as long as everyone accepts that as long as each method does the job the poster requested then no-one has given a wrong answer and people giving different possibilities is good for the poster as they have many different methods they can try :-)

    I myself started programming on a Commodore +4 which coincidentally only had 16k of memory, so I know where you're coming from...a lot of my coding is about trying to improve speed and do things efficiently...in fact, before learning VB properly about a year ago (I was previously unable to wrap my head around how it all went together, but I eventually managed it) I was writing code in QBX...and I am sure many others here also started or came though a QuickBasic route to get here with VB :-)

  19. #19
    Oi, fat-rag! bushmobile's Avatar
    Join Date
    Mar 2004
    Location
    on the poop deck
    Posts
    5,592

    Re: Find the Last letter in a string containing letters and numbers

    Quote Originally Posted by schoolbusdriver
    At 2Ghz+, bush, who cares! Easily understood + flexible. Nice.
    You'd care if you had millions of them to process
    in this case using a byte array makes it four times faster than using a string.

    Quote Originally Posted by szlamany
    Everytime you learn an algorithm, technique or construct and appreciate why it's this-or-that, fast-or-slow, memory-hog-or-not - that makes you a better programmer in the long run.
    Amen to that

  20. #20
    VB6, XHTML & CSS hobbyist Merri's Avatar
    Join Date
    Oct 2002
    Location
    Finland
    Posts
    6,654

    Re: Find the Last letter in a string containing letters and numbers

    I join in just for the fun of giving competition in the speed market ^_^

    VB Code:
    1. Public Function BeforeNumbers(ByRef Text As String) As String
    2.     Dim lngA As Long, lngB As Long
    3.     For lngA = Len(Text) To 1 Step -1
    4.         lngB = AscW(Mid$(Text, lngA, 1))
    5.         If (lngB = 32& Or (lngB >= 48& And lngB <= 57&)) Then Else Exit For
    6.     Next lngA
    7.     If lngA > 1 Then BeforeNumbers = Left$(Text, lngA)
    8. End Function

    You can do faster of course, but I still set simplicity, shortness and elegancy over the speed in this one (thus no byte array either) I chose the "check for numbers and spaces" line, but it would only be a matter of either adding more detection for special characters or then just setting the alphabets. It all depends on the case: can there be other alphabets besides the English ones?

    Speedwise this code is about two times faster than bushmobile's when compiled. Main reasons being: comparisons stringwise is slow and Select Case is slow.


    I jumped to VB from C64. I remember it being weird I couldn't slow down a program by doing For...Next loops

  21. #21
    Oi, fat-rag! bushmobile's Avatar
    Join Date
    Mar 2004
    Location
    on the poop deck
    Posts
    5,592

    Re: Find the Last letter in a string containing letters and numbers

    i wondered when you'd turn up

    this was the version i was talking about in the post before:
    VB Code:
    1. Private Function Extract(ByVal sText As String) As String
    2.     Dim N As Long, b() As Byte
    3.     b = sText
    4.     For N = UBound(b) - 1 To LBound(b) Step -2
    5.         If (b(N) > 57 Or b(N) < 48) And Not b(N) = 32 Then Exit For
    6.     Next N
    7.     Extract = Left$(sText, N \ 2 + 1)
    8.     ' To get the right half of the string do:
    9.     ' Mid$(sText, N \ 2 + 2)
    10. End Function
    Edit: which would be twice as fast as Merri's code above (compiled)

    that's it - i'm stopping there. I'm not going to get into a speed contest cos I know i'd just loose

  22. #22
    VB6, XHTML & CSS hobbyist Merri's Avatar
    Join Date
    Oct 2002
    Location
    Finland
    Posts
    6,654

    Re: Find the Last letter in a string containing letters and numbers

    Well, you already started it

    VB Code:
    1. 'clsSA.cls
    2. Option Explicit
    3.  
    4. Private Declare Sub RtlMoveMemory Lib "ntdll.dll" (ByRef lpvDest As Any, ByRef lpvSrc As Any, ByVal cbLen As Long)
    5. 'Private Declare Function VarPtrArray Lib "msvbvm50.dll" Alias "VarPtr" (Var() As Any) As Long
    6. Private Declare Function VarPtrArray Lib "msvbvm60.dll" Alias "VarPtr" (Var() As Any) As Long
    7.  
    8. Private SA(5) As Long, iarText() As Integer
    9. Public Function BeforeNumbers(ByVal TextStrPtr As Long, ByVal TextLen As Long) As Long
    10.     Dim lngA As Long
    11.     If TextStrPtr = 0 Or TextLen = 0 Then Exit Function
    12.     SA(3) = TextStrPtr: SA(4) = TextLen
    13.     For lngA = TextLen - 1 To 0 Step -1
    14.         If iarText(lngA) < 65 Then Else Exit For
    15.     Next lngA
    16.     If lngA >= 0 Then BeforeNumbers = lngA + 1
    17. End Function
    18. Private Sub Class_Initialize()
    19.     SA(0) = 1: SA(1) = 2
    20.     RtlMoveMemory ByVal VarPtrArray(iarText), VarPtr(SA(0)), 4&
    21. End Sub
    22. Private Sub Class_Terminate()
    23.     RtlMoveMemory ByVal VarPtrArray(iarText), 0&, 4&
    24. End Sub

    VB Code:
    1. Private Sub Command1_Click()
    2.     Dim lngA As Long, lngStart As Long, strTest As String, strResult As String
    3.     Dim lngResult1 As Long, lngResult2 As Long
    4.     Dim SA As clsSA
    5.     Set SA = New clsSA
    6.    
    7.     strTest = "CV8 7TY0124 121212"
    8.  
    9.     lngStart = GetTickCount
    10.     For lngA = 1 To 300000
    11.         strResult = Extract3(strTest)
    12.     Next lngA
    13.     lngResult1 = GetTickCount - lngStart
    14.    
    15.     lngStart = GetTickCount
    16.     For lngA = 1 To 300000
    17.         strResult = Left$(strTest, SA.BeforeNumbers(StrPtr(strTest), Len(strTest)))
    18.     Next lngA
    19.     lngResult2 = GetTickCount - lngStart
    20.  
    21.     MsgBox "Extract3: " & lngResult1 & vbNewLine & "SA.BeforeNumbers: " & lngResult2
    22.  
    23.     Set SA = Nothing
    24. End Sub

    Life is cruel sometimes Four times faster. This is optimization from the other end compared to my last post: usage becomes harder, but the results speedwise are impressive. This optimization can be counted as "insane" for the task it is done for.

  23. #23
    Oi, fat-rag! bushmobile's Avatar
    Join Date
    Mar 2004
    Location
    on the poop deck
    Posts
    5,592

    Re: Find the Last letter in a string containing letters and numbers

    that's some lightning fast stuff

    you wouldn't mind sticking some comments in the class would you? I've never done much stuff that involves directly moving the memory

  24. #24
    VB6, XHTML & CSS hobbyist Merri's Avatar
    Join Date
    Oct 2002
    Location
    Finland
    Posts
    6,654

    Re: Find the Last letter in a string containing letters and numbers

    VB Code:
    1. 'clsSA.cls
    2. Option Explicit
    3.  
    4. Private Declare Sub RtlMoveMemory Lib "ntdll.dll" (ByRef lpvDest As Any, ByRef lpvSrc As Any, ByVal cbLen As Long)
    5. 'Private Declare Function VarPtrArray Lib "msvbvm50.dll" Alias "VarPtr" (Var() As Any) As Long
    6. Private Declare Function VarPtrArray Lib "msvbvm60.dll" Alias "VarPtr" (Var() As Any) As Long
    7.  
    8. ' SA will be a SAFEARRAY (I used a Long array because it is faster than using UDT)
    9. Private SA(5) As Long
    10. ' iarText will have SA as it's header; by default it has no SAFEARRAY header
    11. Private iarText() As Integer
    12. Public Function BeforeNumbers(ByVal TextStrPtr As Long, ByVal TextLen As Long) As Long
    13.     Dim lngA As Long
    14.     ' if pointer is zero or length is zero, then the return value is zero as well
    15.     If TextStrPtr = 0 Or TextLen = 0 Then Exit Function
    16.     ' set where iarText contents are located in memory
    17.     SA(3) = TextStrPtr
    18.     ' set the length of the data
    19.     SA(4) = TextLen
    20.     For lngA = TextLen - 1 To 0 Step -1
    21.         If iarText(lngA) < 65 Then Else Exit For
    22.     Next lngA
    23.     If lngA >= 0 Then BeforeNumbers = lngA + 1
    24. End Function
    25. Private Sub Class_Initialize()
    26.     ' one dimensional
    27.     SA(0) = 1
    28.     ' two bytes per item
    29.     SA(1) = 2
    30.     ' change header used for iarText to our custom SAFEARRAY
    31.     RtlMoveMemory ByVal VarPtrArray(iarText), VarPtr(SA(0)), 4&
    32.     ' it is just a pointer, four bytes (= long value)
    33. End Sub
    34. Private Sub Class_Terminate()
    35.     ' restore original state (iarText had no SAFEARRAY header, thus it is null)
    36.     RtlMoveMemory ByVal VarPtrArray(iarText), 0&, 4&
    37. End Sub


    Basically this is based on not moving memory. It avoids it as much as possible.

  25. #25
    Oi, fat-rag! bushmobile's Avatar
    Join Date
    Mar 2004
    Location
    on the poop deck
    Posts
    5,592

    Re: Find the Last letter in a string containing letters and numbers

    cheers Merri, i think i'll tackle this tomorrow - my brain hurts now

  26. #26
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: Find the Last letter in a string containing letters and numbers

    Anyone tested my Post #9 for speed.

    Just for the sake of curosity!

    Pradeep
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  27. #27
    VB6, XHTML & CSS hobbyist Merri's Avatar
    Join Date
    Oct 2002
    Location
    Finland
    Posts
    6,654

    Re: Find the Last letter in a string containing letters and numbers

    It doesn't do what is requested so there is no interest to do that. But regarding speed, StrReverse is very slow.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width