Omnis Technical Note TNFN0001January 2005
How to use the strpbrk() and strspn() functions
By Rudolf Bargholz, Omnis developer
For Omnis Studio 4.x and later
I recently discovered the usefulness of the strpbrk() and strspn() functions, so I thought the following might help others solve the problem of checking if values entered in a character variable match those in a mask of available characters.
The definition of the strpbrk(string1, string2) function is as follows:
Returns a substring of string1 from the point where any of the
characters in string2 match string1. If none of the characters in string2
match those in string1 then the function returns an empty string.
This is best explained with an example:
We have an entry field in which only characters, numbers and a comma can be entered. No special characters can be entered. One would solve this using an entry field with $keyevents turned on with the following code:
On evKey
If len(strpbrk(upp(pKey),'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,'))=0&len(pKey)>0
Quit event handler (Discard event)
End If
If pKey has the value #, the strpbrk() function above will return an empty string, as the # is not in the comparison string:
ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,
The Quit event handler (Discard event) will prevent the # from being entered into the entry field. The code len(pKey)>0 will prevent the code triggering if a SystemKey event is generated. Note, the use of the strpbrk() function in this case would be analogous to that of the function:
pos(upp(pKey),'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,').
Calculate #S4 as strpbrk('\','0123456789()
-/') -> #S4=''
Calculate #S4 as strpbrk('/','0123456789() -/') -> #S4='/'
The definition of strspn(string1, string2) is as follows:
Returns the index of the first character in string1 that does not
match any of the characters in the string2. If all characters match, the
function returns a value of "len(string1)+1".
If we want to test if all the characters in a string match those that
are allowed to be entered, we can use the following:
If strspn(upp(PhoneNrString),'0123456789() -/')>len(PhoneNrString)
; The phone number string contains only valid characters. The string only
contains characters from the group 0123456789() -/
End If
If we enter a string 01\5551234 the above strspn() function will return '3', as the third character is not on the group of allowed characters. If we enter a string 01/5551234 the above strspn() function will return '11'. The length of the string is '10'.