Kbase 19535: How to Find all Occurances of a Substring in a String
Autor |
  Progress Software Corporation - Progress |
Acesso |
  Público |
Publicação |
  18/02/2000 |
|
The following user defined function will find all occurances of a given substring with a string.
FUNCTION Occurances RETURNS INTEGER
(cString AS CHARACTER, cSubString AS CHARACTER):
DEFINE VARIABLE cFirstChar AS CHARACTER NO-UNDO.
DEFINE VARIABLE iInstances AS INTEGER NO-UNDO INITIAL 0.
DEFINE VARIABLE iPosition AS INTEGER NO-UNDO INITIAL 1.
ASSIGN cFirstChar = SUBSTRING(cSubString,1).
REPEAT:
ASSIGN iPosition = INDEX(cString,cFirstChar,iPosition).
IF iPosition > 0 THEN
DO:
IF cString BEGINS cSubString THEN
ASSIGN iInstances = iInstances + 1.
ASSIGN iPosition = iPosition + 1.
END.
ELSE
LEAVE.
END.
RETURN iInstances.
END FUNCTION.
As an example, the following code will return a value of 5.
MESSAGE Occurances("CBCBCBCBCBC","CBC") VIEW-AS ALERT-BOX.