1. Strings

Introduction

Accessing Substrings


s = "This is what you have"
first = s[0]                            # "T"
start = s[5..7]                         # "is"
rest  = s[13..]                         # "you have"
last  = s.last                          # "e"
end   = s.lasts(4)                      # "have"
piece = s.lasts(8 .. 5)                 # "you"

# magic substr not usefull (?)

s.subst!(G, "is", "at")

Establishing a Default Value


2 &&& "ee" # -> "ee"
0 &&& "ee" # -> ""

"a" ||| "b" # -> "a"
 "" ||| "b" # -> "b"

x |||= "b"

Exchanging Values Without Using Temporary Variables

(a, b) = (b, a)

Converting Between ASCII Characters and Values

# Char::ord !! int
# Int::chr !! char

"HAL".map(next)                         # "IBM"

Processing a String One Character at a Time


# a string is a list, no pb
println(  "unique chars are: {"an apple a day".uniq.sort}")
println(qq(unique chars are: {"an apple a day".uniq.sort}))

Reversing a String by Word or Character

println(s.rev)                          # reverse letters
println(s.words.rev.join(" "))          # reverse words

long_palindromes = cat("/usr/dict/words").map(chomp).filter(s -> s == s.rev && s.size > 4)

Expanding and Compressing Tabs

s.expand_tabs = s.fixpoint(
    break(, "\t",
          a,b -> a + " ".times(8 - a.size modulo 8) + b
    )
)

Expanding Variables in User Input


# forbidden, use one of:
s = "You owe {debt} to me"
fs(s) = "You owe {s} to me"
fs':= sprintf("You owe %s to me",)

"I am 17 years old".subst(G, "(\d+)", (n -> "{2 * n}"))
"I am 17 years old".subst(G, "(\d+)", *2 ~ to_string)

Controlling Case

e = "bo peep".upcase
e.downcase!
e.capitalize!

"thIS is a loNG liNE".words.map(capitalize)

Interpolating Functions and Expressions Within Strings

println("I have {n + 1} guanacos.")

w = "work"
very := () -> "very"
well() = "well"
"this is gonna {w} {very()} {well()}"

Indenting Here Documents

Reformatting Paragraphs

s.wrap(width) =
    ls, s' = s.words.foldl(([], ""), ((ls, s), word ->
        if "{s} {word}" > width then
            ls + [s], word
        else
            s' = (s &&& "{s} ") + word
            ls, s'
    ))
    join(ls + [s'], "\n")
    

Escaping Characters

Trimming Blanks from the Ends of a String

s.subst!("^\s+", "")
s.subst!("\s+$", "")

s.trim = s.subst("^\s+", "").subst("\s+$", "")

Parsing Comma-Separated Data

Soundex Matching

Program: fixstyle

Program: psgrep