Library tutorials & articles

String Functions

Trailing nulls from in a string

When using WindowsAPI, if the function returns a string, it will always be returned with a whole load of null characters after the actual text. You can use this simple function to get rid of them!

Function StripTerminator(ByVal strString As String) As String
    Dim intZeroPos As Integer
    intZeroPos = InStr(strString, Chr$(0))
    If intZeroPos > 0 Then
        StripTerminator = left$(strString, intZeroPos - 1)
    Else
        StripTerminator = strString
    End If
End Function

Comments

  1. 14 Jan 2007 at 17:00

    Here we go again:

    After hours of debugging, I found out the only instance the first word on the second line does not get picked up is when I physically tab or hit enter and enter or type additional text.  In a multiline textbox if VB forces text to next line, the first word will get picked on that second line.  So to VB the text is seemingly one straight line though it it adds the additional text below because the textbox ran out of room.  Hopefully this makes sense...We're good now.  Thanks for reading :-)

  2. 14 Jan 2007 at 03:27

    Replying to my own post...Hiya!

    I found out the trick to grabbing the first word in the string using the above code:

    InStr(1," " & YourString & " ", " " & YourSearchString & " ", vbBinaryCompare)

    Here in the problem we're now facing.  I am not able to read the first word on the next line.  say we had:

    • Watch out for those manholes covers, they're loose, 
    • the woman before you almost fell in

    Watch (first line) gets picked up

    the (second line) does not

    I have been asking around about this.  Will continue toying around with the code and will report my findings.  Any sort of hints you have, I'll play around with it see what happens. 

    Thanks for your assistance.  In a bit!

    KöllMorgan

     

  3. 13 Jan 2007 at 17:52

    Hello!

     

    Wonderful, helpful site, by the way...

     

    I am working on a small program for a friend and noticed the below code.  Works flawlessly, accept that it is not selecting the first word in a Text.  I have attempted different tactics to get it to do what I would like to no avail.  Can you assist me?

     

    Sub Command1_Click()
        ' Get the first occurrence of the string
        StringPos = InStr(1, txtSearchString, txtFindString, vbTextCompare)
        If StringPos = 0 Then
            ' If StringPos returns 0, then the string is not found
            Msgbox "String not found"
        Else
            ' Get the length of the string to find
            StringLen = Len(txtFindString)
            ' Set the starting position of the selection
            txtSearchString.SelStart = StringPos
            ' Set the selection length
            txtSearchString.SelLength = StringLength
        End If
    End Sub













     

    • txtSearchString collects, for instance, "Watch out for those manhole covers, they're loose; the woman before you almost fell in"
    • txtFindString holds the text to find, thus "Watch"

     I am not able to get the code to grab "Watch".  If woman is searched, it is found.  Is there anything else I need to do tom force VB 6.0 to output "Watch" as the first position in the text.  Again, the code is excellent as is, just need it to do a bit more.  txtSearchString.SelStart = StringPos -1 did not seem to work...Please advise. 

     

    Have a great week-end!

    KöllMorgan

     

  4. 06 Dec 2005 at 12:58
    i know i am answering to an oldest question left unanswered..

     but.. i just wanted to answer it..

     just for some one who is searching on a specific topic ...and end up in finding only questions...
     
    like wat i am doing now..

    dont try to trim "     perlandra"
    instead do this...
         bookTitle = "     Perelandra"
         booktitle=trim(booktiltle)
    ..
    bye,
    KOTI.
  5. 17 Feb 2005 at 07:58

    I included a code extract here but you have to click on "read comments" to see it all.


    Basically it just searches the text string for 2 spaces in row, and replaces it with one space, then repeats until theres arent any double spaces left.




    Private Sub MyString_AfterUpdate()
    Dim  MyString
    Dim Done


    MyString = " " & MyString 'adds a space at the start and end of the string (important but difficult to explain)


    Do Until Done      'removes excess spaces in the text string
      If InStr(1, MyString, "  ") = 0 Then
           Done = True
       Else
           MyString = Replace(MyString, "  ", " ")
       End If
    Loop


    MyStringlen = Len(MyString)
    MyString = Right(MyString, MyString
    len - 1) 'removes any spaces at the front, there should always be one at this point (thats why we added one at the start).
    MyString = UCase(MyString) ' converts to uppercase (optional)


    Me.MyString = MyString
    End Sub


    I know it is a long winded way of doing it, but the advantage is that it removes the spaces; before, after, and reduces any excess spaces within a string down to just 1 space each time.  "  camel    dog fish       cat    " to "camel dog fish cat". Yep im sure my repeated use of "MyString" as a variable is "bad" but it works.


  6. 25 Feb 2004 at 19:09

    I have a string set up as follows:
    bookTitle = "     Perelandra"


    I want to trim it down to be:
    bookTitle = "Perelandra"


    However, no variations on the Trim, LTrim and RTrim commands seem to work on the variables.  Is there code for trim the text stored in a variable?



    Edit: Under further analysis, I realized the the space before the title was actually a tab character.  Is there a way to time those off easily?

  7. 08 May 2003 at 15:06

    VB is not the language to do this in.
    With C++ you could load a DLL named in a string but you can't with VB. There's no point dreaming about loading DLL's dynamically through VB.
    Also VB you could create controls at run time but it would be harder than writing it in C++. You'd have to subclass the form and it would get very difficut.
    I haven't got much time at the mo, but i'll post back with more in a day or two.
    Hope it helps!

  8. 07 May 2003 at 17:40

    Aah, I see. Now, do I use VBScript or my own limited command system? Lol. I'ma go with the script here. But... Couldn't users just make custom DLLs with preset function names and my program call them? And as for the GUI, what do you suggest? This program is an editor for various games so they may need to make anything. If, say, a file contained the name of a control type, could I read that into a string and create that control on a form? I know I have a lot of questions but I've never made something like this before.

  9. 07 May 2003 at 15:08

    I don't think there's any point in trying. I'm sure with a few spare months you could get it to work but you'd be much better off learning C++ in those months and adding DLL. (C++ allows dynamic DLL loading if you didn't guess)
    Also, you might have mistaken the answer i gave you. You can't fill a text file with VB code and expect it to run. The CallByName lets you call a function by it's name which is in a string. This means you can only run what is in the sub/function.
    You can use this to create a scripting language and you'll have to program the entire interperator. If you can't see doing this then try the VBScript control (it should be there somewhere, it's an ocx in the list) This will let you write files of pure VBScript (as you can guess it's similar to VB ) and run them. There should be a few articles out there on the VBScript control.


    Hope it helps!

  10. 06 May 2003 at 17:34

    Hmm, sounds like a plan. Basically the users would just write VB code and the program executes it? Cool, but is there some simple way for a user to create a form (like loading a .frm file and using it as an actual form) or would I have to have some datafile with positions for all the controls?

  11. 14 Apr 2003 at 13:14

    You can use the val function:
    long=Val(string)

  12. 11 Apr 2003 at 12:11

    I can hardly remember this post!
    1 Apr 2002 02:35 PM
    more than a year ago. lol


    Ne way
    i've learned a bit more since then and the key to your questions is this function:
    CallByName
    Yep, it does exactly what it says on the tin. Calls any function by it's name, which might not sound any good since you can call functions in VB. BUT, You could load code into a string and call it by line using the split function:


    Dim strData()   as string
    Dim varArgs()  as string
    Dim i               as long
    Dim strText      as string


    strData = Split(strText, vbCrLf)
    For i = 0 to uBound(strData)
     'Execute
     CallByName(FunctionClass, Left$(strData(i), vbMethod, varArgs)
    Next i


    That should do it, but you'll want to work on the variable coding to actually get them from the loaded code and not supply blank ones.
    I haven't tested it so i've no idea if it'l work, but i'll run thru it ne way.
    The variables are declared first (duh)
    Then strData is sized (internally by the split command)
    The split command then splits strText by the 'Carridge Return & Line Feed' (vbCrLf) and fills each split string into a seperate index of the variable (in order of course)
    Then we start a for loop through the entire array
    Each run we call the specified function (in the FunctionClass which will be a safe class with only the externally accessable variables and no real OOP)
    Then the loop continues.
    Im sure you can work in that. A tip is to use functions to create variables (actually have an array of a user-type with a name string and a variant variable)
    Anything you don't understand post back here


    Hope it helps!

  13. 10 Apr 2003 at 23:19

    How would I go about converting a number in a string to a Long value? Even more so, a hex number in a string?

  14. 10 Apr 2003 at 23:16

    I was thinking the same. I'm making an editor for some games and would like it if users could just hack up some simple code and have my program run it to add support for other things, but I haven't a clue how I would do it.

  15. 27 Feb 2003 at 14:44

    But if you have VB6 then there's already a builtin-function called split().
    It's very easy to use:

    Code:
    arrayWithSplittedData = Split(variableToSplit, "|")


    /Chill

  16. 19 Aug 2002 at 21:37
    is it normal to forget to notice you posted here and come back a few months later thinking wtf?

    have fun with what you just found...
  17. 19 Aug 2002 at 21:21
    Exactly what I was looking for, Thanks
  18. 26 May 2002 at 06:35

    im not sure if this will get what you want but heres something different useing the Split function:


    Dim strText as string
    dim sResult1 as string, sResult2 as string, result3 as string, res4 as string


    strtext= "the|boy|is|evll" "
    sResult1 = Split(strtext, "|")(0)
    sResult2 = Split(strtext, "|")(1)
    Result3 = Split(strtext, "|")(2)
    res4= Split(strtext, "|")(3)


    Hope that helps!


    Good Luck!



  19. 26 May 2002 at 05:04

    Use the bit of code below.  Just replace the msgbox with the rel. storage code.




       Dim OrigText As String
       Dim Orig
    TxLen As Byte
       Dim Rem
    Text As String
       Dim RemTxLen As Byte
       Dim DelimPos As Byte
       Dim Word
    Text As String
       
       
       OrigText = "the|boy|is|evil"
       Orig
    TxLen = Len(OrigText)
       
       RemText = OrigText
       
       While Not RemTxLen = OrigTxLen
       
       
           If InStr(1, RemText, "|") > 0 Then
               
               Delim
    Pos = InStr(1, RemText, "|") - 1
               Word
    Text = Left(RemText, DelimPos)
               RemText = Right(RemText, Len(RemText) - Len(WordText) - 1)
             
           Else
               
               WordText = RemText
               RemTxLen = OrigTxLen
                       
           End If
       
       MsgBox (Word_Text)
       
       
       Wend



  20. 10 Apr 2002 at 08:34

    Say if i had


    the|boy|is|evil


    exactly wat i need to break up, into string 1,2,3,4 by the|????

  21. 01 Apr 2002 at 14:35

    Is it possible to create 'plug-ins' for a vb app?
    It would be handy to be able to release 'add-ons' to programs i am making - for example - If new formats were released it would be handy to be able to have an add-in that upgrades the program?
    Any ideas?


    Thanks

  22. 01 Apr 2002 at 13:47

    is there a funtion that splits a string into an array by a certain character?


    Say if i had


    the|boy|is|evil


    and if i split it by "|" it would put "the" into array_whatever(0)


    n/m i got it...


         Option Explicit
         Public Function Split(ByVal sIn As String, Optional sDelim As _
               String, Optional nLimit As Long = -1, Optional bCompare As _
                VbCompareMethod = vbBinaryCompare) As Variant
             Dim sRead As String, sOut() As String, nC As Integer
             If sDelim = "" Then
                 Split = sIn
             End If
             sRead = ReadUntil(sIn, sDelim, bCompare)
             Do
                 ReDim Preserve sOut(nC)
                 sOut(nC) = sRead
                 nC = nC + 1
                 If nLimit <> -1 And nC >= nLimit Then Exit Do
                 sRead = ReadUntil(sIn, sDelim)
             Loop While sRead <> ""
             ReDim Preserve sOut(nC)
             sOut(nC) = sIn
             Split = sOut
         End Function

  23. 03 Jan 2002 at 14:41

    To convert the first letter of each word to upper case, use the StrConv function:
    Dim strText as String
    strText = "monday 24 july 2001"
    strText = StrConv(strText,vbProperCase)


    this will return "Monday 24 July 2001"

  24. 03 Jan 2002 at 08:54

    Hi


    I  need some help making the first character in a word large.
    I have a date, monday 23 july 2001.
    I need for det 'm' i monday to be large.


    This is my date function:
    strDate = Now()
    intDay = Day(strDate)
    strWeekDayName = WeekDayName(WeekDay(strDate))
    intThisMonth = MonthName(Month(strDate))
    intYear = Year(strDate)


    I have tried using mid function and ucase, but I keep getting smal characters og just the furst charachter in the month.


    Jannike

  25. 01 Jan 1999 at 00:00

    This thread is for discussions of String Functions.

Leave a comment

Sign in or Join us (it's free).

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...

Related discussion

Related podcasts

  • Christian Beauclair

    14 mai 2008 (�mission #0074) ::.Christian Beauclair: Stratégies de migration VB6 vers .NET Nous discutons avec Christian Beauclair des stratégies de migration VB6 vers .NET. Entre autres, nous discutons comment utiliser le "VB 6 Code Advisor" et le "Interop Forms Toolkit" pour ajouter la puiss...

We'd love to hear what you think! Submit ideas or give us feedback