Hello I need to write my own mid function, have do I do that, just someone know, I know the mid function definition is mid(String, Start As Long, [Length]), if I wanted to create my own function, how do I do that, does someone have an example
There are a couple of ways to tackle this problem. I would personally make a function that splits the string into an array, and then grab the passed number as that array's indice. I have attached a project that has 3 functions in it. The first I'll go over is str2Array, which takes each character in a string, and puts it into an array, 1 character per indice. The str2Array function requires the use of another function, spush (String Push), which just sticks elements onto an array, like a stack. It simplifies having to deal with dynamic arrays by rediming every time you want to add a new element to the array. The last is the actual mymid function, which takes 2 arguments (the string, and the starting point), and an optional 3rd argument, which is the length to return to the calling procedure. Something to note about this function, is that it too, just like the actual Mid function, returns the entire rest of the string if the length passed to it is greater than the end of the string. So, for example, if the string is "hello world", and you tell the function to start at character 6, and go a length 15, it will just return world, and not error out. A serious difference, though, (which can be fixed fairly easily) is that the actual Mid function reads the first character of a string as 1, while the mymid function starts reading strings at 0. You can change this easily enough by using an option base, and making a minor change to the if statement in the mymid function, but I'll leave those for you to play with.
oops, fixing it, standby (I just realized that str2Array uses Mid, that's kind of a conflict of idea's, huh?)... just replace the old str2array with this one:
Public Function str2Array(xString As String) As String() Dim tmpArray() As String Dim B() As Byte Dim tmpchar As String B() = xString For I = 0 To UBound(B) Step 2 spush tmpArray, Chr(B(I)) Next I str2Array = tmpArray End Function
Basically, it assigns the string to a byte array. The byte array contains numbers instead of letters, but the numbers directly coorispond to the letters, so we use chr with the character code to get the letter. We push that onto our array, and then return it to the calling procedure. This method is actually a lot faster than using the mid function (with larger amounts of data), because it doesn't have to make a bunch of copies of the string, AND it's working with bytes.