星期一, 11月 06, 2023

2004-01-13 如何於 RPG 中產生唯一的數字及文字混合字串?(GENUNISTR)


如何於 RPG 中產生唯一的數字及文字混合字串?(GENUNISTR)

我們時常會有產生單一且唯一的字串當作 Key 鍵值,例如:訂單編號,一般最常用的是使用數字欄位
自動累加 1 產生,但是若有文數字混合時該如何產生呢?下列範例是初始值為 10 位
長的文數字其初值為"000000ZZZW",程式會自動累加 1 ,以算出下一個值,
DSPLY  000000ZZZX
DSPLY  000000ZZZY
DSPLY  000000ZZZZ
DSPLY  0000010000
DSPLY  0000010001
DSPLY  0000010002
DSPLY  0000010003
DSPLY  0000010004
DSPLY  0000010005
DSPLY  0000010006
教你如何達成這個目的。


File  : QRPGLESRC
Member: GENUNISTR
Type  : RPGLE
Usage : CRTBNDRPG GENUNISTR
        CALL GENUNISTR
OS Version: V5R1

     D counters        c                   '0123456789+
     D                                     ABCDEFGHIJKLMNOPQRSTUVWXYZ'

     D string          s             10a   inz('000000ZZZW')

     D i               s             10i 0
     D cur             s             10i 0
     D digit           s             10i 0
     D lastChar        s              1a
     D firstChar       s              1a
     D curChar         s              1a

     C                   Eval      firstChar = %subst(counters : 1 : 1)
     C                   Eval      lastChar =
     C                                 %subst(counters : %len(counters) : 1)
     C*      // "add" 1 to the string 10 times
     C                   for       i = 1 to 10

     C*      // this does the "adding"
     C                   for       digit = %len(string) downto 1
     C                   eval      curChar = %subst(string : digit : 1)
     C                   eval      cur = %scan(curChar : counters)
     C                   if        cur = %len(counters)
     C                   eval      %subst(string : digit : 1) = firstChar
     C*      // we have to "carry the 1" to the next digit
     C                   else
     C                   eval      %subst(string : digit : 1) =
     C                             %subst(counters : cur + 1 : 1)
     C*            // done; we have added the 1 to the current digit
     C                   leave
     C                   endif
     C                   endfor
     C     string        dsply

     C                   endfor

     C                   eval      *inlr = '1'



沒有留言: