Clojure:
Extracting substrings
How to:
Clojure makes it easy to work with strings. For extracting substrings, subs
is your go-to function:
(let [text "ClojureRocks"]
(subs text 7)) ; => "Rocks"
(let [text "ClojureRocks"]
(subs text 0 7)) ; => "Clojure"
And that’s it—give it a start index, and optionally an end index, and you’ll chop the string just how you need it.
Deep Dive
Extracting substrings isn’t new—been around since the early days of programming. In Clojure, subs
is a straightforward function. It’s part of Clojure’s Java interop capabilities, piggybacking on Java’s substring
method. Two key points: negative indices aren’t allowed, and it’s zero-based (starts counting at zero). So remember that or you’ll be one off.
Alternatives? Sure. Regex with re-find
and re-matcher
for complex patterns, or split
if you’re dividing at a delimiter. Each tool has its place, but nothing beats subs
for simplicity.
Implementation-wise, subs
doesn’t copy characters, it shares the original string’s character array. Efficient, but if your original string is huge and all you need is a tiny bit, you might inadvertently keep the whole big string in memory.
See Also:
- Official Clojure String API: clojure.string
- Java
substring
: Because that’s the powerhouse behindsubs
. Java substring - Regular expressions in Clojure: re-find
- Splitting strings in Clojure: split