New string manipulation functions for Common Lisp

vindarel

vindarel

Posted on March 17, 2023

New string manipulation functions for Common Lisp

Hi lispers o/

I started the str library as a n00b, to fix my first frustration with Common Lisp: string manipulation. It received great contributions and it is now used by a bunch of people, great! Special thanks to @kilianmh (openapi-generator) for his continuous style improvements, bug fixes, reviews and new features.

The str library ((ql:quickload "str")) provides short and consistent functions, such as: concat, join, trim, collapse-whitespace, pad, shorten, words, unwords, lines, split, to-file, from-file, empty, blankp, containsp, starts-with-p, ends-with-p, replace-all, downcase[p] and friends, replace-using, remove-punctuation

We recently added some functions: ensure-prefix, ensure-suffix, ensure-wrapped-in, ensure and wrapped-in-p.

Example:

(str:ensure-prefix "/" "abc/") => "/abc/" (a prefix was added)
Enter fullscreen mode Exit fullscreen mode

ensure-prefix makes sure that the string starts with the given prefix. If it's already there, it does nothing.

ensure-suffix does what you guess,

ensure-wrapped-in is here to do both checks at once:

(str:ensure-wrapped-in "/" "abc") ;; => "/abc/"  (added both a prefix and a suffix)
Enter fullscreen mode Exit fullscreen mode

here it added "/" to both the start and the end of our string. And here it won't add anything:

(str:ensure-wrapped-in "/" "/abc/") ;; => "/abc/" (does nothing)
Enter fullscreen mode Exit fullscreen mode

ensure can do everything at once. Its signature is the following:

 (ensure s &key wrapped-in prefix suffix)
Enter fullscreen mode Exit fullscreen mode

If wrapped-in is provided, it will ignore prefix and suffix if they are also provided.

Example:

(str:ensure "abc" :wrapped-in "/")  ;; => "/abc/"
(str:ensure "/abc" :prefix "/")  ;; => "/abc"  => no change, still one "/"
(str:ensure "/abc" :suffix "/")  ;; => "/abc/" => added a "/" suffix.
Enter fullscreen mode Exit fullscreen mode

If both :prefix and :suffix are provided, it simply calls the two necessary "ensure-" functions.

Another useful improvement: the trim function only accepted whitespaces. It now accepts a :charbag key parameter, so you can trim any character from the string.

So yeah, my examples are sort of dealing with URIs. When you need real URI handling, look at Quri.

That's all o/

These "ensure-" functions are to appear in the next Quicklisp release of April, 2023. You can grab the library on Ultralisp or clone it into your ~/quicklisp/local-projects.

To learn more about string manipulation in CL, look at the Cookbook: https://lispcookbook.github.io/cl-cookbook/strings.html

💖 💪 🙅 🚩
vindarel
vindarel

Posted on March 17, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related