<< Back to SWIFT
Swift Substring Examples
Get a substring from a string with a range. Use index, startIndex and offsetBy.String range, substring. In Swift 4 a substring is taken in many ways. Strings cannot be directly indexed by Ints. But we can use ranges to take substrings.
With startIndex and endIndex, we access character offsets in strings. We use index() to move past the start and end. With the resulting range, we get a substring.
First example. This program takes a substring of a string. We first create a range. We use the half-open range operator on the endIndex of the "name" string.
Start: We call index() on the string and pass startIndex and an offsetBy int to get the start of the range. We advance 4 chars.
Result: We skip past the first 4 characters of "The Grapes of Wrath." The resulting substring starts with Grapes.
Swift program that uses index
let name = "The Grapes of Wrath"
// Get range based on the string index.
let r = name.index(name.startIndex, offsetBy: 4)..<name.endIndex
// Access substring from range.
let result = name[r]
print(result)
Output
Grapes of Wrath
Example 2. This example is similar, but uses a different end. We isolate the middle substring "two" of our input string. We use index() to omit the first 4 and last 6 characters.
End: The exclusive end is based on the endIndex of the string. We move backwards 6 chars from the end of the string.
Result: The substring is returned by indexing the string with the range. It equals "two."
Swift program that gets substring
// This is the input string.
let s = "one two three"
// Get range 4 places from the start, and 6 from the end.
let r = s.index(s.startIndex, offsetBy: 4)..<s.index(s.endIndex, offsetBy: -6)
// Access the string by the range.
let substring = s[r]
print(substring)
Output
two
End substring. Sometimes we want to base a substring on the end of the string. Here we call index() to adjust the start index of the range by 6 chars.
And: We leave the end index alone. The resulting substring is the end of the original string.
Swift program that gets end substring
let value = "bird, lizard and fish"
// Get range of all characters past the first 6.
let range = value.index(value.startIndex, offsetBy: 6)..<value.endIndex
// Access the substring.
let substring = value[range]
print(substring)
Output
lizard and fish
RemoveSubrange. This func can be used to create substrings. We specify the range of the string we want to remove. The string is modified to have only the remaining characters.
Here: We remove the first 6 characters from the string. We pass a range to the removeSubrange method.
Range: We base our range on the string's startIndex. It covers the start to six places past the start.
Var: We must use the var keyword declare the string "dotnetCodex" here. The string is modified by removeSubrange.
Swift program that removes range from string
var name = "dotnetCodex"
// Remove the first 6 characters from this string.
// ... We begin at startIndex.
// ... We continue until startIndex advanced by 6 chars.
name.removeSubrange(name.startIndex..<name.index(name.startIndex, offsetBy: 6))
print(name)
Output
Codex
Substring after char. This program introduces a secondWord method. It searches for a space in the argument string. It then returns the substring after that space character.
Index of: We use the "index of" method to search for a space in secondWord. We then use "if let" to see if the space was found.
Finally: We use the index we just computed as the start. We return a substring based on the range of the start to the string's endIndex.
Returning string: In Swift 4 we cannot directly return a string from a subscript. We must return the String() with a special call.
Swift program that gets substring after space
func secondWord(value: String) -> String {
// Find index of space.
if let space = value.index(of: " ") {
// Return String.
// ... Use "after" to avoid including the space.
// Use String() to for Swift 4.
return String(value[value.index(after: space)..<value.endIndex])
}
return ""
}
// Test our func.
print(secondWord(value: "orange cat"))
print(secondWord(value: "black dog"))
print(secondWord(value: "multicolored parrot"))
Output
cat
dog
parrot
Index before, after. We can use index to search for a character in a string. And we can use index() to get the index before or after another index.
Here: We use these index methods on a simple string. This shows how the index method changes its results based on its arguments.
Swift program that uses index of, before, after
let colors = "blue,red,green"
// Get character indexes.
let indexE = colors.index(of: "e")!
let indexComma = colors.index(of: ",")!
// Get before and after indexes.
let indexBeforeE = colors.index(before: indexE)
let indexAfterE = colors.index(after: indexE)
let indexBeforeComma = colors.index(before: indexComma)
let indexAfterComma = colors.index(after: indexComma)
// Get substrings based on ranges.
print("IndexE: \(colors[indexE..<colors.endIndex])")
print("IndexComma: \(colors[indexComma..<colors.endIndex])")
print("IndexBeforeE: \(colors[indexBeforeE..<colors.endIndex])")
print("IndexAfterE: \(colors[indexAfterE..<colors.endIndex])")
print("IndexBeforeComma: \(colors[indexBeforeComma..<colors.endIndex])")
print("IndexAfterComma: \(colors[indexAfterComma..<colors.endIndex])")
Output
IndexE: e,red,green
IndexComma: ,red,green
IndexBeforeE: ue,red,green
IndexAfterE: ,red,green
IndexBeforeComma: e,red,green
IndexAfterComma: red,green
Single char, StartIndex. To access a character from a string, we must use an index (not an Int). Here we use startIndex to get the first char in the string "Puma."
Swift program that accesses char from string
let value = "Puma"
// A string's chars can be accessed with startIndex or endIndex.
let char = value[value.startIndex]
print(char)
Output
P
Int subscript. A string cannot be indexed by an Int. Characters in a string may be different lengths. So we must access strings with ranges based on startIndex and endIndex.
Swift program that causes Int subscript error
let value = "lion"
// A string cannot be accessed with Ints.
var char = value[0]
Output
main.swift:3:12: 'subscript' is unavailable: cannot subscript String with an Int
Returning String error. In Swift 4 and beyond we must return a String with a special call. We cannot just return the result of a subscript directly.
Note: The error is shown in this example, and the fix to this error is shown afterwards.
Swift program that causes returning String error
func removeFirst2Chars(value: String) -> String {
// We need to wrap this in a String call.
return value[value.index(value.startIndex, offsetBy: 2)..<value.endIndex]
}
print(removeFirst2Chars(value: "xxy"))
Output
program.swift:3:9: error:
subscripts returning String were obsoleted in Swift 4; explicitly construct a String from subscripted result
Returning String, fix. Here is the special call to String() to return a string from a func. The subscript expression is wrapped inside a String() func call.
Swift program that returns String correctly
func removeFirst2Chars(value: String) -> String {
return String(value[value.index(value.startIndex, offsetBy: 2)..<value.endIndex])
}
print(removeFirst2Chars(value: "xxy"))
Output
y
A Swift note. In Swift 1 through 3 substring operations have changed significantly. In Swift 2 we had advancedBy on string indexes. But in Swift 3 we have index().
And: In Swift 4 usage of "characters" is deprecated, and we must call String() when returning a new substring from a function.
In Swift, strings must be accessed by ranges based on the startIndex and endIndex. This is because chars are not all the same size. Substrings become less intuitive.
Related Links:
- Swift String Append Example: reserveCapacity
- Swift File (Read Text File Into String)
- Swift Find Strings: range of Example
- Swift Subscript Example
- Swift hasPrefix and hasSuffix Examples
- Swift Array of Dictionary Elements
- Swift Tutorial
- Swift Odd and Even Numbers
- Swift Operator: Equality, Prefix and Postfix
- Swift Dictionary Examples
- Swift Class Example: init, self
- Swift Combine Arrays: append, contentsOf
- Swift Initialize Array
- Swift Int Examples: Int.max, Int.min
- Swift 2D Array Examples
- Swift Error Handling: try, catch
- Swift Repeat While Loop
- Swift Optional: Nil Examples
- Swift Replace String Example
- Swift Print: Lines, Separator and Terminator
- Swift inout Keyword: Func Example
- Swift Lower, Uppercase and Capitalized Strings
- Swift enum Examples: case, rawValue
- Swift Padding String Example (toLength)
- Swift UIActivityIndicatorView Example
- Swift UIAlertController: Message Box, Dialog Example
- Swift UIButton, iOS Example
- Swift UICollectionView Tutorial
- Swift UIColor iOS Example: backgroundColor, textColor
- Swift UIFont Example: Name and Size
- Swift UIImageView Example
- Swift UIKit (Index)
- Swift UILabel Tutorial: iPhone App, Uses ViewController
- Swift String
- Swift Remove Duplicates From Array
- Swift If, If Else Example
- Swift Caesar Cipher
- Swift UIStepper Usage
- Swift UISwitch: ViewController
- Swift UITableView Example: UITableViewDataSource
- Swift UITextField: iPhone Text Field Example
- Swift UITextView Example
- Swift UIToolbar Tutorial: UIBarButtonItem
- Swift UIWebView: LoadHtmlString Example
- Swift Var Versus Let Keywords
- Swift Math: abs, sqrt and pow
- Swift Reverse String
- Swift Struct (Class Versus Struct)
- Top 22 Swift Interview Questions (2021)
- Swift Substring Examples
- Swift Switch Statements
- Swift Convert Int to Character: UnicodeScalar, utf8
- Swift Property Examples
- Swift isEmpty String (characters.count Is Zero)
- Swift Recursion
- Swift ROT13 Func
- Swift Convert String to Byte Array: utf8 and UInt8
- Swift Keywords
- Swift Convert String to Int Example
- Swift Join Strings: joined, separator Examples
- Swift String Literal, Interpolation
- Swift Extension Methods: String, Int Extensions
- Swift Characters: String Examples
- Swift Func Examples: Var, Return and Static
- Swift Guard Example: Guard Else, Return
- Swift Fibonacci Numbers
- Swift Trim Strings
- Swift Set Collection: Insert and Contains
- Swift Tuple Examples
- Swift Loops: for, repeat and while Examples
- Swift Split Strings Example (components)
- Swift Array Examples, String Arrays
- Swift UIPickerView Example: UIPickerViewDataSource
- Swift UIProgressView Example: Progress
- Swift UISegmentedControl
- Swift UISlider Example
- Swift Random Numbers: arc4random
- Swift ASCII Table
- Swift Range Examples (index, offsetBy)
- Swift String Length
- Swift Sort String Arrays: Closure Examples
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf