Back to General

Operations on Lists (Iterators & Amend) · General · Practice Question

Reverse the Order of Underscore-Separated Words

Sign in to track your progress

Question

Given:

s:"aaa_bbb_ccc"

Convert s to "ccc+bbb+aaa" — the same words, in reverse order, joined with + instead of _.

Expected result:

"ccc+bbb+aaa"

Solution

"+" sv reverse "_" vs s

Explanation

"_" vs s splits s on every underscore, turning it into a list of words:

q)"_" vs s
"aaa"
"bbb"
"ccc"

reverse flips the order of that list of words:

q)reverse "_" vs s
"ccc"
"bbb"
"aaa"

"+" sv (...) then joins the reversed list of words back into a single string, using + as the separator instead of the original _. vs (split) and sv (join) are inverses of each other, which is why this pattern — split, transform the list of pieces, join back together — comes up so often for text manipulation in q.