Pure Programmer
Blue Matrix


Cluster Map

Strings

L1

This page is under construction. Please come back later.

At their heart, a string is simply a sequence of characters. Characters, in turn, are encoded as integers using encoding schemes such as [[ASCII]], [[ISO-Latin-1]] or [[Unicode]]. So a string is simply a sequence of integers. Languages like FORTRAN or C that don't support strings as a fundamental type, actually treat strings as a sequence of integers. Modern programming languages support strings as a fundamental data type which make them much easier to use and manipulate.

Strings are particularly useful when conveying information to the user in contrast to being useful for computation like integers or floating point values. While strings are typically implemented as an array/list of the more basic character type, modern languages provide a string data type that encapsulates the characters of a string and provide functionality for working with strings. When using strings in our programs there are two types of strings: [[literal]] strings and string variables.

Variables and Literals

String literals are string values that are directly written in the program itself. String literals only represent the one string as it is typed into the code. String literals are enclosed in double quotes . String literals can be used any place a string is required.

"Hello, world!"
"My name is: \(name)"
"Four score and seven years ago..."
"z"

Example String Literals

String literals in Swift allow for variable interpolation by placing a variable name in a string surrounded by the \(...) symbols. By placing a variable inside a string literal, Swift will substitute into the string the current value of the variable.

String variables are like any other variable. This means that string variables must be declared before they can be used and must follow the variable naming rules discussed in the variables section. that is they can be set and reset to different values at will. Unlike variables of the primitive types such as boolean, integer and floating point, string variables represent an entire string of characters. String variables can be set using string literals or other string variables.

Concatenation

One of the most basic operations we can perform on strings is called concatenation. Concatenation takes two strings and forms a new one by appending the second string on to the end of the first string. Using concatenation we can build up a complex string from small strings. In Swift the concatenation operator is the + (plus) symbol.

Strings1.swift
#!/usr/bin/env swift;
/******************************************************************************
 * This program demonstrates string concatenation.
 * 
 * Copyright © 2020 Richard Lesh.  All rights reserved.
 *****************************************************************************/

import Foundation

// Begin Main
let a:String = "one"
let b:String = "two"
let c:String = "three"
var d:String = a + b + c
print(d)
d = a + "\t" + b + "\n" + c
print(d)

exit(EXIT_SUCCESS)

Output
$ swiftc Strings1.swift -I . -L . -lUtils error: link command failed with exit code 1 (use -v to see invocation) ld: library not found for -lUtils clang: error: linker command failed with exit code 1 (use -v to see invocation)

Operations on Strings

Swift supports a number of operations on strings. The most often used is determining the length of a string. [an error occurred while processing this directive] Counting the characters in a string is accomplished using the length() method. Some of the other string operations available are summarized in the following table.

String Operations
Fixed PointScientific Notation
00e0
3.14153.1415e0
Strings2.swift
#!/usr/bin/env swift;
/******************************************************************************
 * This program demonstrates basic string functions.
 * 
 * Copyright © 2020 Richard Lesh.  All rights reserved.
 *****************************************************************************/

import Foundation
import Utils

// Begin Main
let alphabet:String = "abcdefghijklmnopqrstuvwxyzabc"
let greekAlphabet:String = "αβγδεζηθικλμνξοπρσςτυφχψωαβγ"
let emoji:String = "😃😇🥰🤪🤑😴🤒🥵🥶🤯🥳😎😥😱😡🤬💀👽🤖😺🙈🙉🙊😃😇🥰"

print("Length: " + String(alphabet.count))
print("charAt(17): " + String(Utils.substr(alphabet, 17, 18)))
print("codePointAt(17): " + String(Utils.codepoint_at(alphabet, 17)))
print("substr(23, 26): " + Utils.substr(alphabet, 23, 26))
print("prefix(6): " + alphabet.prefix(6))
print("right_tail(6): " + Utils.substr(alphabet, 6))
print("suffix(6): " + alphabet.suffix(6))
print("find(\'def\'): " + String(alphabet.indexOf("def")))
print("find(\'def\') is not found: " + String((alphabet.indexOf("def") == -1)))
print("find(\'bug\'): " + String(alphabet.indexOf("bug")))
print("find(\'bug\') is not found: " + String((alphabet.indexOf("bug") == -1)))
print("rfind(\'abc\'): " + String(alphabet.lastIndexOf("abc")))
print("rfind(\'abc\') is not found: " + String((alphabet.lastIndexOf("abc") == -1)))
print("rfind(\'bug\'): " + String(alphabet.lastIndexOf("bug")))
print("rfind(\'bug\') is not found: " + String((alphabet.lastIndexOf("bug") == -1)))

print("Length: " + String(greekAlphabet.count))
print("charAt(17): " + String(Utils.substr(greekAlphabet, 17, 18)))
print("codePointAt(17): " + String(Utils.codepoint_at(greekAlphabet, 17)))
print("substr(23, 26): " + Utils.substr(greekAlphabet, 23, 26))
print("prefix(6): " + greekAlphabet.prefix(6))
print("right_tail(6): " + Utils.substr(greekAlphabet, 6))
print("suffix(6): " + greekAlphabet.suffix(6))
print("find(\'δεζ\'): " + String(greekAlphabet.indexOf("δεζ")))
print("find(\'δεζ\') is not found: " + String((greekAlphabet.indexOf("δεζ") == -1)))
print("find(\'bug\'): " + String(greekAlphabet.indexOf("bug")))
print("find(\'bug\') is not found: " + String((greekAlphabet.indexOf("bug") == -1)))
print("rfind(\'αβγ\'): " + String(greekAlphabet.lastIndexOf("αβγ")))
print("rfind(\'αβγ\') is not found: " + String((greekAlphabet.lastIndexOf("αβγ") == -1)))
print("rfind(\'bug\'): " + String(greekAlphabet.lastIndexOf("bug")))
print("rfind(\'bug\') is not found: " + String((greekAlphabet.lastIndexOf("bug") == -1)))

print("Length: " + String(emoji.count))
print("charAt(16): " + String(Utils.substr(emoji, 16, 17)))
print("codePointAt(16): " + String(Utils.codepoint_at(emoji, 16)))
print("substr(20, 24): " + Utils.substr(emoji, 20, 24))
print("prefix(6): " + emoji.prefix(6))
print("right_tail(6): " + Utils.substr(emoji, 6))
print("suffix(6): " + emoji.suffix(6))
print("find(\'😱😡🤬\'): " + String(emoji.indexOf("😱😡🤬")))
print("find(\'😱😡🤬\') is not found: " + String((emoji.indexOf("😱😡🤬") == -1)))
print("find(\'bug\'): " + String(emoji.indexOf("bug")))
print("find(\'bug\') is not found: " + String((emoji.indexOf("bug") == -1)))
print("rfind(\'😃😇🥰\'): " + String(emoji.lastIndexOf("😃😇🥰")))
print("rfind(\'😃😇🥰\') is not found: " + String((emoji.lastIndexOf("😃😇🥰") == -1)))
print("rfind(\'bug\'): " + String(emoji.lastIndexOf("bug")))
print("rfind(\'bug\') is not found: " + String((emoji.lastIndexOf("bug") == -1)))

exit(EXIT_SUCCESS)

Output
$ swiftc Strings2.swift -I . -L . -lUtils error: link command failed with exit code 1 (use -v to see invocation) ld: library not found for -lUtils clang: error: linker command failed with exit code 1 (use -v to see invocation)

Comparing Strings

Like numeric types, string types are comparable. This means that we can order strings and determine which ones are lower and which ones are higher in that ordering. Strings are ordered using [[Lexicographical Order]] also know as Alphabetic or Dictionary Order. This is done by comparing the first characters of the two strings to determine which string is lower and which is higher. If the first characters are the same, we move on to the second character in each string and so on until a difference is found. Shorter strings always compare lower than a longer string that has the lower string as its prefix. Like numeric types, we have six comparison operators that allow us to determine how two strings compare lexicographically.

String Comparison Operators
OperatorMeaning
==equal to
!=not equal to
<less than
<=less than or equal
>greater than
>=greater than or equal
Strings3.swift
#!/usr/bin/env swift;
/******************************************************************************
 * This program demonstrates string comparisons.
 * 
 * Copyright © 2020 Richard Lesh.  All rights reserved.
 *****************************************************************************/

import Foundation
import Utils

// Begin Main
let color1:String = "Blue"
let color2:String = "Red"
var result:Bool

print("compare(color1, color2): " + String(Utils.compareTo(color1, color2)))
result = color1 < color2
print("color1 < color2: " + String(result))
result = color1 > color2
print("color1 > color2: " + String(result))
result = color1 == color2
print("color1 == color2: " + String(result))
result = color1 != color2
print("color1 != color2: " + String(result))

exit(EXIT_SUCCESS)

Output
$ swiftc Strings3.swift -I . -L . -lUtils error: link command failed with exit code 1 (use -v to see invocation) ld: library not found for -lUtils clang: error: linker command failed with exit code 1 (use -v to see invocation)

Character Types

Often it is necessary to determine what class an individual character belongs. Character classes such as alphabetic, numeric, whitespace, control and punctuation are common classes of characters in which we would be interested. The following table illustrates how we would determine the class of a character.

Strings4.swift
#!/usr/bin/env swift;
/******************************************************************************
 * This program illustrates some of the string functions in Utils
 * 
 * Copyright © 2020 Richard Lesh.  All rights reserved.
 *****************************************************************************/

import Foundation
import Utils

let ltrstr:String = "   Spaces to the left"
let rtrstr:String = "Spaces to the right  "
let trimstr:String = "   Spaces at each end   "
let blank:String = "  \t\n  "
let lowerstr:String = "This String is Lowercase"
let upperstr:String = "This String is Uppercase"

// Begin Main
print(String("|") + Utils.ltrim(ltrstr) + String("|"))
print(String("|") + Utils.rtrim(rtrstr) + String("|"))
print(String("|") + Utils.trim(trimstr) + String("|"))
print(String("|") + Utils.trim(blank) + String("|"))
print(String("|") + lowerstr.lowercased() + String("|"))
print(String("|") + upperstr.uppercased() + String("|"))

exit(EXIT_SUCCESS)


Output
$ swiftc Strings4.swift -I . -L . -lUtils error: link command failed with exit code 1 (use -v to see invocation) ld: library not found for -lUtils clang: error: linker command failed with exit code 1 (use -v to see invocation)
Character Classification
FunctionDescription
isalnum(c)Check if character is alphanumeric.
isalpha(c)Check if character is alphabetic.
isblank(c)Check if character is blank.
iscntrl(c)Check if character is a control character.
isdigit(c)Check if character is decimal digit.
isgraph(c)Check if character has graphical representation.
islower(c)Check if character is lowercase letter.
isprint(c)Check if character is printable.
ispunct(c)Check if character is a punctuation character.
isspace(c)Check if character is a white-space.
isupper(c)Check if character is uppercase letter.
isxdigit(c)Check if character is hexadecimal digit.

Character Conversion
FunctionDescription
tolower(c)Returns lowercase version of the character.
toupper(c)Returns uppercase version of the character.
swift

Questions

Projects

More ★'s indicate higher difficulty level.

References