Thursday 19 April 2012

String Functions 1

Here are the first few lines of our object data again.
tool,1
resource,2
device,3
job,4
In order to transfer the information to the correct fields in the object array, we need to be able to identify the different parts in the line.

Looking at it, it seems obvious, the name is the part before the comma, the icon number is the part after.

In programming terms, we need to search for the comma, which is in a different position on each line.

While the routine to do that is simple enough, it would be better if we had a general function which could find any string inside any other string.

Better still would be a function that could find several things without having to keep checking the entire string.

To address this, we have a number of short general purpose string functions, the first of which is a basic sub-string search called FindSubString().
function FindSubString( thisString$ , thisSearch$ , thisStart )
   thisLen = len( thisSearch$ )
   thisSearch$ = upper( thisSearch$ )
   thisString$ = upper( thisString$ )
   thisEnd = len( thisString$ ) - thisLen + 1
   for thisPos = thisStart to thisEnd
      if mid( thisString$ , thisPos , thisLen ) = thisSearch$ then exit
   next i
   if thisPos > thisEnd then thisPos = 0
endfunction thisPos
This looks for the first occurrence of the string thisSearch$ in the string thisString$, starting at the position specified in thisStart.  If it finds one it returns the position, if not it returns zero.

The function can be tested with the following code in the main loop.
String$ = "Hello World"
Search$ = "lo"
found = FindSubString( String$ , Search$ , 1 )
print( Search$ + " in " + String$ + " at position " + str( found ))
Which looks for the string "lo" inside the string "hello world" starting at position 1. The result should look like this.
Feel free to try a few different search strings to make sure it finds them all, and when you've done, remove the test code.

The same call can now be used in our load function.

Before we do that, let's change the code in the main loop to show the contents of the object array rather than the temp array.

Change the lines.
// Intro Code
print(" Lines : " + str( testNum ) )
for i=1 to testNum
   print( str(i) + " : " + tempArray[ i ] )
next i
print( " ----- ")
To.
print(" Objects : " + str( TopObject() ) )
for i=1 to TopObject()
   print( str(i) + " : " + ObjectName( i ) + " : " + str( ObjectIcon( i ) ) )
next i
print( " ----- ")
So that it's now using the object array rather than the temp array.

Compile and run the program and you should get.
As there are no objects in the array yet.

No comments:

Post a Comment