Search code examples
stringpari-gp

Is there a better way to get substring in PARI/gp?


? substr(s,n,m)=concat(Vec(s)[n..n+m-1])
%1 = (s,n,m)->concat(Vec(s)[n..n+m-1])
? s="h0getcwdfailedNosuchfileordirectory"
%2 = "h0getcwdfailedNosuchfileordirectory"
? substr(s,4,8)
%3 = "etcwdfai"

Question: Is there a better way (built-in function?) to get substring in PARI/gp?


Solution

  • Not really. Here's a faster hack (also using less memory)

    substr2(s,n,m)=strchr(Vecsmall(s)[n..n+m-1])
    

    Timing this on your example:

    ? substr2(s,4,8)
    %1 = "etcwdfai"
    ? for(i=1,10^6,substr(s,4,8))
    time = 536 ms.
    ? for(i=1,10^6,substr2(s,4,8))
    time = 266 ms.