Exercise 02 Strings - MikeyYeahYeah/clojure-koans GitHub Wiki
Chapter 02 - Strings
String (str) Function
(str 'hello)
=> "hello"
- You can also use the
strfunction to combine terms
(str 'hello " world")
=> "hello world"
Get Function
Returns the value mapped to key, not-found or nil if key not present. If used on a string, you can pass an index position an retrieve a character
Note: The \C indicates that this is a character
(get "Characters" 0 )
=> \C
Count Function
Count the characters in a string
(count "Hello World")
=> 11
Subs
Returns the substring of s beginning at start inclusive, and ending at end (defaults to length of string), exclusive.
(sub "Hello World" 6 11)
=> "World"
Working with the Clojure String Library
clojure.string/join
Note: In order to use clojure.string, you must import it into your name space. This can be done using the require function. Additionally, you can call it and rename it to make using it a bit easier. You would use (require '[clojure.string :as string]) to call it in and use it as the symbol string
You can use string/join to combine strings together...
(string/join '(1 2 3))
=> "123"
Or you can even insert characters between each element
(string/join ", " '(1 2 3))
=> "1, 2, 3"
clojure.string/split-lines
Splits s on \n or \r\n
(string/split-lines "1\n2\n3")
=> "1" "2" "3"
clojure.string/reverse
Reverse a string
(string/reverse "hello")
=> "elloh"
clojure.string/index-of
Return index of value (string or char) in s, optionally searching forward from from-index or nil if not found. In other words, you can add an integer telling the indexer which element to start at as in the 3rd example below.
(index-of "ababc" "a")
;;=> 0
(index-of "ababc" "ab")
;;=> 0
(index-of "ababc" "ab" 1)
;;=> 2
clojure.string/last-index-of
Return last index of value (string or char) in s, optionally searching backward from from-index or nil if not found. In layman's terms, The integer indicates to start at position x and look back from that point for the term.
(last-index-of "abcde" "c")
;;=>2
(last-index-of "abcde" "e" 3)
;;=> nil
(last-index-of "abcde" "e" 4)
;;=> 4
clojure.string/trim
Removes whitespace from both ends of string. Note: Escape sequences count as white space and will be removed"
(string/trim " \nhello world \t \n")
;;=> "hello world"
Querying Strings
Is it a character?
(char? \c)
;;=> true
(char? "c")
;;=> false
Is it a string?
(string? \b)
;;=> false
(string "b")
;;=> true
Is it blank?
Note: This function is a part of the clojure.string library. In addition, escaped characters don't count as characters.
(string/blank? "")
;;=> true
(string/blank? " \n \t")
;;=> true
(string/blank? "Pizza \t and \t Turkey")
;;=> false