如何在PostScript中将字符串分割为数组?

5

如何以给定字符为分隔符将字符串拆分成数组?例如,通过空格拆分单词的数组;甚至可以制作字符串的所有字符的数组。

我能想到的唯一方法是在循环中使用search。由于所有语言都有此目的的函数,我担心我在PostScript中遗漏了一个这样的函数。


1
我在这里的回答中有一个使用循环搜索的示例:http://stackoverflow.com/a/5846955/733077 - luser droog
2个回答

8
%!

%(string) (delimiter)  split  [(s)(t)(r)(i)(n)(g)]
/split {              % str del
    [ 3 1 roll        % [ str del
    {                 % [ ... str del
        search {      % [ ... post match pre
            3 1 roll   % [ ... pre post match  %ie. [ ... pre str' del
        }{            % [ ... str
            exit       % [ ... str  %% break-from-loop
        }ifelse
    }loop             % [ ...
    ]                 % [ ... ]
} def

(string of words separated by spaces)( )split ==
%-> [(string) (of) (words) (separated) (by) (spaces)]

(string.of.words.separated.by.dots)(.)split ==
%-> [(string) (of) (words) (separated) (by) (dots)]

6

使用 search 操作符是正确的选择。它的作用是执行文本字符串搜索和匹配。下面是在PostScript 语言参考手册中找到的 search 操作符摘要:

search   string seek search post match pre true (if found)  
         string false (if not found)  

         looks for the first occurrence of the string seek within string and  
         returns results of this search on the operand stack. The topmost   
         result is a boolean that indicates if the search succeeded.  

         If search finds a subsequence of string whose elements are equal   
         to the elements of seek, it splits string into three segments:   
         pre, the portion of string preceding the match; match, the portion  
         of string that matches seek; and post, the remainder of string. It  
         then pushes the string objects post, match, and pre on the operand   
         stack, followed by the boolean true. All three of these strings are  
         substrings sharing intervals of the value of the original string.  

         If search does not find a match, it pushes the original string  
         and the boolean false.  

         Example:  

             (abbc) (ab) search ==> (bc) (ab) ( ) true  
             (abbc) (bb) search ==> (c) (bb) (a) true  
             (abbc) (bc) search ==> () (bc) (ab) true  
             (abbc) (B) search ==> (abbc) false  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接