Swift
String Manipulation
Programming
Swift Tutorials
Code Snippets

How do I check if a string contains another string in Swift?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Swift, checking if a string contains another string is a common task that can be accomplished using several methods. This article will explore these methods in detail, providing code examples and technical explanations.

Checking String Containment in Swift

Swift provides robust string manipulation capabilities, including methods to check if one string contains another. The primary method used for checking containment is the contains(_:) method, which belongs to the String type.

Using contains(_:) Method

The contains(_:) method is straightforward and is the most idiomatic way to check for a substring in Swift. It is part of the String protocol and returns a Boolean indicating whether the string contains another specified string.

swift
1let mainString = "Hello, World!"
2let searchString = "World"
3
4if mainString.contains(searchString) {
5    print("The main string contains the search string.")
6} else {
7    print("The main string does not contain the search string.")
8}

In this example, mainString.contains(searchString) evaluates to true because "Hello, World!" indeed contains the substring "World".

Technical Explanation

  • The contains(_:) method is case-sensitive, meaning that "world" would not be found within "World".
  • It performs a locale-aware comparison that respects Unicode character boundaries.

Case-Insensitive Containment

If you need to perform a case-insensitive check, you can convert both strings to lowercase or uppercase before using contains(_:).

swift
1let mainString = "Hello, World!"
2let searchString = "world"
3
4if mainString.lowercased().contains(searchString.lowercased()) {
5    print("The main string contains the search string (case-insensitive).")
6} else {
7    print("The main string does not contain the search string (case-insensitive).")
8}

Using Range and range(of:) Method

For more complex scenarios, such as finding the range in which a substring appears, you can use the range(of:) method. It returns an optional Range<String.Index> that represents the index range of the substring if found.

swift
1let mainString = "Hello, World!"
2let searchString = "World"
3
4if let range = mainString.range(of: searchString) {
5    print("The substring is found from index \(range.lowerBound.utf16Offset(in: mainString)) to \(range.upperBound.utf16Offset(in: mainString)).")
6} else {
7    print("The substring is not found.")
8}

Technical Explanation

  • The range(of:) method can accept options like .caseInsensitive, .byWords, and .anchored for more sophisticated searching.
  • The result is of type Range<String.Index>?, which makes it suitable for tasks like text highlighting or editing.

Regular Expressions

For advanced pattern matching, you may employ regular expressions using NSRegularExpression.

swift
1import Foundation
2
3let mainString = "Hello, World!"
4let searchPattern = "world"
5let regex = try NSRegularExpression(pattern: searchPattern, options: .caseInsensitive)
6
7let range = NSRange(location: 0, length: mainString.utf16.count)
8if regex.firstMatch(in: mainString, options: [], range: range) != nil {
9    print("The main string matches the pattern (using regex).")
10} else {
11    print("The main string does not match the pattern (using regex).")
12}

Technical Explanation

  • NSRegularExpression allows for more flexible pattern searching, including options for case insensitivity and complex patterns.
  • It requires converting String indices to NSRange.

Summary Table

Below is a table summarizing the key methods for string containment in Swift:

MethodDescriptionCase Sensitivity
contains(_:)Checks if a string contains a substringSensitive
contains(_:) with lowercased()Case-insensitive check by converting both strings to lowercase or uppercaseInsensitive
range(of:)Finds the range of a substring within a stringSensitive
range(of:options:)Advanced search with options like .caseInsensitiveConfigurable
NSRegularExpressionPattern matching using regular expressionsConfigurable

Conclusion

Swift provides several methods for checking the presence of one string in another, each with its use cases and features. The choice between them should consider factors like case sensitivity and performance needs. Understanding and utilizing these functionalities will allow for efficient and tailored string manipulations within your Swift applications. Whether you need a simple substring check or complex pattern matching, Swift's string handling APIs offer the tools necessary to accomplish the task.


Course illustration
Course illustration

All Rights Reserved.