This month we have a function for character replacement for the tip corner.
This originates from a message posted on the Liberty Basic forum. Someone was looking for a solution to a problem. They said I am storing a directory listing in a string and some of these directories have spaces in them like:
Cars & Bikes
I need to take out these spaces and make the string = Cars&Bikes
So, here is some code that I offer to accomplish the task. I have made the replacement task is a simple function that is reusable. I have tried to get enough comments in there so that you can tell what is happening.
a$ = "Cars & Bikes" 'remove any spaces and replace with null string b$ = replaceChar$(a$, asc(" "), 0) print a$ print b$ a$ = "Cats & Dogs" 'replace any ampersand with a space b$ = replaceChar$(a$, asc("&"), asc(" ")) print a$ print b$ 'replace any space with an ampersand a$ = "This is my string" b$ = replaceChar$(a$, asc(" "), asc("&")) print a$ print b$ input c$ function replaceChar$(source$, asciiFind, asciiReplace) 'function will search a string for the ascii value supplied 'in asciiFind and replace all accurances with the ascii value 'found in asciiReplace - use of ascii values supports non- 'printable characters. 'find length of source string sLen = len(source$) work$ = "" 'make sure we don't have a zero length string if sLen > 0 then 'now scan for spaces using a while loop curPos = 0 while 1 = 1 'increment position counter curPos = curPos + 1 'see if we are at end of string if curPos > sLen then Exit while 'see if this is a string value to replace if asc(mid$(source$,curPos,1)) = asciiFind then 'if the replacement value is zero the remove the character if asciiReplace > 0 then work$ = work$ + chr$(asciiReplace) end if else work$ = work$ + mid$(source$,curPos,1) end if wend end if 'now return a value replaceChar$ = work$ end function
Notice that the function takes a source string and then two numeric values. The numeric variables are ASCII values for the character you want to replace and what to replace it with. Use the LB function ASC to find ASCII values of characters. If you want to replace a character with a NULL then pass 0 (zero) as the last argument. I decided to allow ASCII values because it allows greater functionality.