Hi folks,
Here's a function I had to write today; it "increments" a character string
to generate the next one in sequence, the idea being to follow spreadsheet
column naming i.e. A-Z, AA-AZ etc. You specify the current value as an input
parameter to the function, and it returns the next one. I've not used
functions much, so all comments are welcome!
Cheers,
Nick
<BLOCKQUOTE><font size="1" face="Arial, Verdana">code:</font><HR><pre>
FUNCTION next-code RETURNS CHAR (INPUT ip-code AS CHAR).
DEF VAR lv-a AS INT NO-UNDO.
DEF VAR lv-b AS INT NO-UNDO.
/* If being called for the first time, */
/* just return a letter "A". */
IF ip-code = "" THEN RETURN "A".
/* Starting at the right end of the string, */
/* look for a non-z character. If one is */
/* found, increment it and set any chars to */
/* the right of it to "A"s. */
code-loop:
DO lv-a = LENGTH(ip-code) TO 1 by -1:
IF SUBSTR(ip-code,lv-a,1) <> "Z" THEN DO:
SUBSTR(ip-code,lv-a,1) = CHR(ASC(SUBSTR(ip-code,lv-a,1)) + 1).
DO lv-b = lv-a + 1 TO LENGTH(ip-code):
SUBSTR(ip-code,lv-b,1) = "A".
END.
RETURN ip-code.
END.
END.
/* To get this far, the string must contain */
/* all "Z"s, so we need to increase the */
/* length of the string and set everything */
/* to "A"s. */
RETURN FILL("A",LENGTH(ip-code) + 1).
END FUNCTION.
[/code]
Here's a function I had to write today; it "increments" a character string
to generate the next one in sequence, the idea being to follow spreadsheet
column naming i.e. A-Z, AA-AZ etc. You specify the current value as an input
parameter to the function, and it returns the next one. I've not used
functions much, so all comments are welcome!
Cheers,
Nick
<BLOCKQUOTE><font size="1" face="Arial, Verdana">code:</font><HR><pre>
FUNCTION next-code RETURNS CHAR (INPUT ip-code AS CHAR).
DEF VAR lv-a AS INT NO-UNDO.
DEF VAR lv-b AS INT NO-UNDO.
/* If being called for the first time, */
/* just return a letter "A". */
IF ip-code = "" THEN RETURN "A".
/* Starting at the right end of the string, */
/* look for a non-z character. If one is */
/* found, increment it and set any chars to */
/* the right of it to "A"s. */
code-loop:
DO lv-a = LENGTH(ip-code) TO 1 by -1:
IF SUBSTR(ip-code,lv-a,1) <> "Z" THEN DO:
SUBSTR(ip-code,lv-a,1) = CHR(ASC(SUBSTR(ip-code,lv-a,1)) + 1).
DO lv-b = lv-a + 1 TO LENGTH(ip-code):
SUBSTR(ip-code,lv-b,1) = "A".
END.
RETURN ip-code.
END.
END.
/* To get this far, the string must contain */
/* all "Z"s, so we need to increase the */
/* length of the string and set everything */
/* to "A"s. */
RETURN FILL("A",LENGTH(ip-code) + 1).
END FUNCTION.
[/code]