Sling Academy
Home/Swift/Swift: 3 Ways to Check if a String Contains a Substring

Swift: 3 Ways to Check if a String Contains a Substring

Last updated: February 23, 2023

This succinct, practical article walks you through 3 different approaches to checking if a string contains a substring or not. Without any further ado, let’s get started.

Using the contains() method

The contains() method is a built-in method of String type in Swift. It returns a boolean value indicating whether the given string contains the specified substring.

Example:

let str = "The sky is blue and the grass is green"
if str.contains("blue") {
    print("Substring found")
} else {
    print("Substring not found")
}

Output:

Substring found

Using the range(of:) method

The range(of:) method is another built-in method of String type in Swift. It returns an optional Range object representing the range of the specified substring in the given string or nil if the substring is not found.

Example:

import Foundation

let str = "Sling Academy provides Swift tutorials"
if str.range(of: "Sling Academy") != nil {
    print("Substring found")
} else {
    print("Substring not found")
}

Output:

Substring found

See also: Optional, Nil, and Nil Check in Swift

Using Regular Expressions

Using regular expressions can be tough in some cases, but in return, it is very flexible and powerful.

The example below demonstrates how to use regular expressions to check if a string contains a substring in Swift while ignoring case sensitivity:

import Foundation

let str = "Sling Academy is a great place to learn magic."
let subStr = "academy"
let pattern = "\\b\(subStr)\\b"
let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let range = NSRange(location: 0, length: str.utf16.count)

if regex.firstMatch(in: str, options: [], range: range) != nil {
    print("Substring found in string")
} else {
    print("Substring not found in string")
}

Output:

Substring found in string

In the code above, we define a regular expression pattern called pattern that matches the substring subStr, with the \b character indicating that the match should only occur at a word boundary. The NSRegularExpression class is used to compile the regular expression pattern into a regular expression object with the .caseInsensitive option set. The firstMatch(in:options:range:) method is used to search for the first match of the regular expression in the string str.

Next Article: Swift: 3 ways to count the occurrences of words in a string

Previous Article: 2 Ways to Reverse a String in Swift

Series: Working with Strings in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)