Smalltalk by example: String data handling
Basic strings (character collections) are created using the special syntax, using two quotes to generate a string with a quote.
"Create a simple string, with single quote" 'Well I''m a simple string.' printNl ! "Generates Well I'm a simple string."
TODO: Special characters.
Commonly used accessors of the String class are self-explanatory:
'Hello' size ! "Returns 5, the number of bytes in the string" 'Hello' first ! "Returns the first character: $H" 'Hello' last ! "Returns the last character: $o"
The characters can then be tested:
'Hello' first isUppercase ! "Returns a Boolean: true" 'Hello' last isUppercase ! "Returns a Boolean: false"
The following functions can also be applied to the characters: isAlphaNumeric isDigit isLetter isLowercase isPunctuation isSeparator isUppercase isVowel.
A string is a collection of characters. So, we can request the index of an element (a character) with String.indexOf:. To find a substring (remember a String is a sequencedCollection) you will need to use indexOfSubCollection:. Both of these functions have an ifAbsent: variant, which accepts a block if the element or Collection could not be found.
"Finding a character" 'the target string' indexOf: $t ! "Returns 1" "Using ifAbsent block" 'the target string' indexOf: $z ifAbsent: [ 0 ] ! "Returns 0" "Finding a substring" 'the target string' indexOfSubCollection: 'target' ! "Returns 5" "Using the ifAbsent" 'the target string' indexOfSubCollection: 'needle' ifAbsent: [ 'Not found' ]! "Returns 'Not found'"
If you suspect multiple occurences, you can count them using. Count substrings with countSubCollectionOccurrencesOf:. Count characters (elements) with occurencesOf:.
"Counting characters" 'the target string' occurrencesOf: $t ! "Returns 4" "Counting substrings" 'A cow says moooo' countSubCollectionOccurrencesOf: 'oo' ! "Returns 2"
Search and replace
Back to GST by example