To check if a string contains a given substring in Swift, you can use the contains
method of the String class.
In this example,
str
with a string value.contains
method of the string object str
to check if it contains the substring "World"
.contains
method returns a Boolean value indicating whether the substring is found.import Foundation
let str = "Hello World"
let containsSubstring = str.contains("World")
print("String contains 'World': \(containsSubstring)")
String contains 'World': true
In this example,
str1
with a string value.contains
method of the string object str1
to check if it contains the substring "Swift"
.contains
method returns a Boolean value indicating whether the substring is found.import Foundation
let str1 = "Hello Swift"
let containsSubstring = str1.contains("Swift")
print("String contains 'Swift': \(containsSubstring)")
String contains 'Swift': true
In this example,
str2
with a string value.contains
method of the string object str2
to check if it contains the substring "Python"
.contains
method returns a Boolean value indicating whether the substring is found.import Foundation
let str2 = "Hello Swift"
let containsSubstring = str2.contains("Python")
print("String contains 'Python': \(containsSubstring)")
String contains 'Python': false
In this tutorial, we learned How to Check if a String contains given Substring in Swift language with well detailed examples.