GST Strings

219,584pages on
this wiki
Add New Page
Discuss this page0 Share

Smalltalk by example: String data handling

Creating strings

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.

Inspecting strings

Common accessors

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.

Finding substrings

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"

Changing strings

Search and replace


Back to GST by example

Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.

Also on Fandom

Random wikia