Skip to content
Tutorials Center
My learning

Topics

Lesson 91 of 146 Β· Standard Library and Foundation

Text Processing

Learn practical Swift text processing - split, components, trimming, searching and replacing, lines, words and Character properties, with a word-frequency program and the pitfalls of Unicode.

A huge share of real programs are text programs. They read a log file, split a CSV row, clean up user input, find a word, count lines, or turn " Hello, World " into something tidy. Swift's String is excellent for this, but it is also different from the strings in many other languages, so a little practice pays off.

In Strings you learned how String, Character and indices work. This lesson is the toolbox on top: splitting, trimming, searching, replacing, lines and words, and Character properties. You will finish with a small word-frequency program that combines everything. Most of the functions here live in the standard library; a few come from Foundation, and each example says which import it needs.

Splitting a string

The most common job is cutting a string into pieces. The standard library's split works on any collection, so it works on strings. You give it a separator Character and get back an array of Substrings.

Swift split and its options

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Four things to notice:

  1. By default split drops empty pieces, so the double comma in "ada,,grace" vanishes. Pass omittingEmptySubsequences: false when the empty fields matter, as they do in real CSV where an empty column is data.
  2. maxSplits: 1 stops after the first cut and leaves the rest of the string together in the last piece.
  3. The separator can be a whole string such as "--".
  4. The result type is [Substring], not [String]. A Substring is a cheap view into the original string's memory. That is fast, but a Substring keeps the whole original string alive, so convert with String(piece) when you store it for a long time.

Foundation adds components(separatedBy:), which returns [String] and keeps empty pieces. You will see it a lot in older code.

Swift components(separatedBy:) from Foundation

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

This prints the four fields including the empty one, 4, and then ["a", "b", "", "c", "", "", "d"], because every digit is a separator. In new code prefer split, which is in the standard library, is faster, and lets you choose whether to keep empties. Use components(separatedBy:) when you want [String] straight away or a CharacterSet.

To join pieces back, use joined(separator:):

Swift
let words = ["swift", "is", "fun"]
print(words.joined(separator: " "))   // swift is fun

Trimming and cleaning

User input arrives with stray spaces, tabs and newlines. Foundation's trimmingCharacters(in:) removes characters from both ends of a string, never from the middle.

Swift Trimming whitespace and other characters

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first line prints [Hello, World!]: the three spaces between the words stay, because trimming only looks at the ends. Splitting on spaces and re-joining collapses them to [Hello, World!], a useful trick since split discards the empty pieces. trimmingPrefix(_:) removes a prefix only if it is there and is standard library, no Foundation needed.

Searching

Swift gives you several levels of searching, from yes/no questions to exact positions.

Swift Searching inside strings

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The results are true, true, true, false, true, then found at offset 4, matched: quick, The appears 2 times (the second "the" before "lazy" is lowercase, so it does not count), and finally everything before the first period.

Key points:

  • hasPrefix, hasSuffix and contains are quick yes/no checks. Matching is exact, and "exact" for Swift means Unicode canonical equivalence: "Γ©" written as one scalar equals "Γ©" written as e plus a combining accent.
  • firstRange(of:) and ranges(of:) return ranges of String.Index. You cannot use an integer offset with a string, so you slice with the range itself, as in text[range].
  • For case-insensitive or accent-insensitive searches use the Foundation methods such as localizedCaseInsensitiveContains and range(of:options:). A simple alternative is to compare lowercased() copies.

If you try to treat a string like an array of characters you hit Swift's most famous error:

Swift Integer subscripts on a String (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

TEXT
main.swift:2:13: error: 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.

The reason is that characters have different sizes in memory, so finding the third one means walking the string. Swift makes that cost visible. Use word[word.index(word.startIndex, offsetBy: 2)], or convert to an array of characters when you need random access: let letters = Array(word).

Replacing and transforming

Swift Replacing, changing case, reversing

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first line replaces only the lowercase cats and prints I like dogs. Cats are great.; with .caseInsensitive both are replaced, and the capital C is replaced by the lowercase text you passed: I like dogs. dogs are great.. capitalized upper-cases the first letter of each word (Hello World). The reversal prints desserts, and the filter keeps only the consonants of education, giving dctn.

Reversing and slicing work on Characters, which are user-perceived characters (grapheme clusters). An emoji with a skin tone or a flag stays in one piece. If you convert to utf8 or unicodeScalars first, you can break such characters apart, so do that only when you really need bytes.

Lines and words

Text from files and the console is made of lines. The right test for "is this a line break" is Character.isNewline, which covers \n, \r\n, and the Unicode line and paragraph separators in one go.

Swift Lines, words and counting

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Expect lines: 4, then 1 -> 3 words, 2 -> 3 words, 3 -> 0 words, 4 -> 6 words, then non-blank: 3 and longest: Fourth line after a blank one. Look at the first split: passing omittingEmptySubsequences: false keeps the empty third line, which is why there are four lines, not three.

enumerateLines calls a closure for every line, so it can update a local variable like longest. It is handy when you want Foundation's exact line-break rules, but the split version above is shorter and works in the standard library alone.

"Word" is a fuzzy idea. Splitting on whitespace is simple and good enough for English text with the punctuation stripped. For accurate word boundaries in every language (Chinese has no spaces), Foundation offers enumerateSubstrings(in:options:) with .byWords.

Character properties

Each Character knows what kind of character it is. These properties are Unicode-aware, so they work for more than ASCII.

Swift Classifying Characters

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Compare the counts with the string yourself: the letters include ÜnΓ― and the Chinese characters ζ•°ε­—, because isLetter is true for any letter in any script. isNumber is also true for the Arabic-Indic digit Ω£ (and wholeNumberValue returns 3 for it), but asciiValue is nil for it, shown as 0 here with ?? 0. Notice Character("ß").uppercased() returns a String, SS, because upper-casing can change the length of the text.

Rule of thumb: use isLetter, isNumber, isWhitespace and friends for classification, and avoid comparisons like ch >= "a" && ch <= "z", which silently ignore every non-English letter.

Putting it together: a word-frequency counter

This program reads text from standard input, lowercases it, strips punctuation, counts the words and prints the top results. The input is preset in the editor, so you can change it and run again.

Swift Word frequency from input

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program prints the: 6, cat: 3, dog: 2, mat: 2, then distinct words: 9. Three decisions are worth copying. Punctuation is replaced with spaces rather than deleted so mat, and cat; do not glue neighbours together. String(word) converts each Substring before it becomes a dictionary key. And the sort breaks ties by key, because a dictionary has no stable order and your output must be deterministic.

For anything more complex than splitting and searching, such as validating an email-like pattern or extracting the numbers from a log line, move up to regular expressions.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does "a,,b".split(separator: ",") return by default?

    split omits empty subsequences by default. Pass omittingEmptySubsequences: false to keep them.
  2. 2. Why does let c = word[2] not compile for a String?

    Integer subscripting would hide an O(n) walk through the string. Use index(_:offsetBy:) or convert to Array(word).
  3. 3. What type does split return the pieces as?

    Pieces are Substrings that share the original string's storage. Convert with String(piece) to keep one long-term.
  4. 4. Which call removes whitespace only from the beginning and end of a string?

    trimmingCharacters only looks at the ends. The other options remove or split on whitespace everywhere in the string.
  5. 5. Why is ch.isLetter better than ch >= "a" && ch <= "z" for classifying text?

    Range comparisons only cover the English alphabet. The Character properties follow Unicode rules for every script.

Summary

  • split(separator:) and split(whereSeparator:) cut a string into [Substring]; empty pieces are dropped unless you pass omittingEmptySubsequences: false. components(separatedBy:) (Foundation) returns [String] and keeps empties.
  • trimmingCharacters(in:) removes characters at both ends only; trimmingPrefix removes a known prefix.
  • hasPrefix, hasSuffix, contains, firstRange(of:) and ranges(of:) search; Foundation adds case- and locale-aware variants.
  • Strings cannot be subscripted with an Int (cannot subscript String with an Int, use a String.Index instead); use indices, ranges, or Array(string).
  • replacing(_:with:) and replacingOccurrences(of:with:options:) replace text; uppercased() can change the length of a string.
  • Split lines with \.isNewline and words with \.isWhitespace, keeping or dropping empty lines on purpose.
  • isLetter, isNumber, isWhitespace, isPunctuation and wholeNumberValue are Unicode-aware; prefer them over ASCII range checks.
  • Sort dictionary results (with a tie-breaker) before printing.

Next: Regular Expressions shows how to match patterns that simple splitting and searching cannot express.