First Word
January 25, 2019
Our version uses string-index
from the Standard Prelude:
(define (first-word str) (substring str 0 (string-index #\space str)))
And here’s our sample problem:
> (first-word "abcdefg hijklmnop qrs tuv wxyz") "abcdefg"
You can run the program at https://ideone.com/tfoYDE.
Extra points for implementing the Unicode default word breaking algorithm: https://unicode.org/reports/tr29/#Word_Boundaries
Two solutions in golang.
Here’s a solution in C.
Example Usage:
AWK version
$ echo "abcdefg hijklmnop qrs tuv wxyz" | awk ‘{ print $1 }’
abcdefg
—
Klong version
(-1)_((a?" ")@0)#a::"abcdefg hijklmnop qrs tuv wxyz"
"abcdef"
a
"abcdefg hijklmnop qrs tuv wxyz"
a?" "
[7 17 21 25]
—
MUMPS version
YDB>w $p("abcdefg hijklmnop qrs tuv wxyz"," ")
abcdefg
That Unicode algorithm looks a bit complicated, here’s a simple Unicode-friendly solution using Python str.isspace():
Python solution:
firstWord = lambda x: x.lstrip(" ").split(" ")[0]