6

How do I concatenate two strings in Postscript?

(foo) (bar) ??? -> (foobar)
Mark Harrison
  • 297,451
  • 125
  • 333
  • 465
  • Refer the below documentation for a list of basic string operations. Including string concatenation.[stringconv](http://www.tinaja.com/glib/strconv.pdf) – DeeGo Aug 18 '17 at 10:21

3 Answers3

10

PostScript doesn't have a built-in string concatenation operator. You need to write some code for that. For instance

 /concatstrings % (a) (b) -> (ab)  
   { exch dup length    
     2 index length add string    
     dup dup 4 2 roll copy length
     4 -1 roll putinterval
   } bind def  

(code from https://en.wikibooks.org/wiki/PostScript_FAQ/Programming_PostScript#How_to_concatenate_strings%3F.)

lhf
  • 70,581
  • 9
  • 108
  • 149
  • you bet... and thanks for the pointer, my program is working well now! – Mark Harrison Sep 12 '12 at 23:06
  • Link rot has taken out the above. See: [How to concatenate strings?](https://en.wikibooks.org/wiki/PostScript_FAQ/Programming_PostScript#How_to_concatenate_strings?) – scruss Dec 28 '21 at 13:42
7

Same idea generalized to any number of strings. Earlier revisions use a helper function acat which takes an array of strings (for easy counting and iteration). This version uses fancier loops and stack manipulation to avoid allocating an array. This version would also concatenate arrays by changing the string operator to array.

% (s1) (s2) (s3) ... (sN) n  ncat  (s1s2s3...sN)
/ncat {        % s1 s2 s3 .. sN n                   % first sum the lengths
    dup 1 add  % s1 s2 s3 .. sN n n+1 
    copy       % s1 s2 s3 .. sN n  s1 s2 s3 .. sN n
    0 exch     % s1 s2 s3 .. sN n  s1 s2 s3 .. sN 0 n 
    {   
        exch length add 
    } repeat             % s1 s2 s3 .. sN  n   len  % then allocate string
    string exch          % s1 s2 s3 .. sN str   n   
    0 exch               % s1 s2 s3 .. sN str  off  n
    -1 1 {               % s1 s2 s3 .. sN str  off  n  % copy each string
        2 add -1 roll       % s2 s3 .. sN str  off s1  % bottom to top
        3 copy putinterval  % s2 s3 .. sN str' off s1
        length add          % s2 s3 .. sN str' off+len(s1)
                            % s2 s3 .. sN str' off'
    } for                               % str' off'
    pop  % str'
} def 

(abc) (def) (ghi) (jkl) 4 ncat == %(abcdefghijkl)
luser droog
  • 18,988
  • 3
  • 53
  • 105
  • This code uses a *bottom-to-top* stack technique described in more detail [here](https://groups.google.com/d/topic/comp.lang.postscript/Ptkxi3tAxkk/discussion). – luser droog Aug 13 '14 at 06:53
3

There are useful subroutines in

http://www.jdawiseman.com/papers/placemat/placemat.ps

including Concatenate (accepting two strings) and ConcatenateToMark (mark string0 string1 …).

Mark Harrison
  • 297,451
  • 125
  • 333
  • 465
jdaw1
  • 225
  • 3
  • 11