Skip to content

Latest commit

 

History

History
65 lines (50 loc) · 1.86 KB

1-01_capitalizing-strings.asciidoc

File metadata and controls

65 lines (50 loc) · 1.86 KB

Changing the Capitalization of a String

by Ryan Neufeld

Problem

You need to change the capitalization of a string.

Solution

Use clojure.string/capitalize to capitalize the first character in a string:

(clojure.string/capitalize "this is a proper sentence.")
;; -> "This is a proper sentence."

When you need to change the case of all characters in a string, use clojure.string/lower-case or clojure.string/upper-case:

(clojure.string/upper-case "loud noises!")
;; -> "LOUD NOISES!"

(clojure.string/lower-case "COLUMN_HEADER_ONE")
;; -> "column_header_one"

Discussion

Capitalization functions only affect letters. While the functions capitalize, lower-case, and upper-case may modify letters, characters like punctuation marks or digits will remain untouched:

(clojure.string/lower-case "!&$#@#%^[]")
;; -> "!&$#@#%^[]"

Clojure uses UTF-16 for all strings, and as such its definition of what a letter is is liberal enough to include accented characters. Take the phrase "Hurry up, computer!" which includes the letter 'e' with both acute (é) and circumflex (ê) accents when translated to French. Since these special characters are considered letters, it is possible for capitalization functions to change case appropriately:

(clojure.string/upper-case "Dépêchez-vous, l'ordinateur!")
;; -> "DÉPÊCHEZ-VOUS, L'ORDINATEUR!"

See Also