How to check if a string contains another string in Swift?
Last Updated :
05 Jul, 2022
The Swift language supports different types of generic collections and a string is one of them. A string is a collection of alphabets. In the Swift string, we check if the specified string is present in a string or not. To do this task we use the contains() function. This function is used to check whether the specified string i.e. sequence of characters is present in the string or not. It will return true if the given string is present in the string otherwise it will return false.
Syntax:
string.contains(char: charSequence)
Here string is an object of the string class.
Parameters: This function accepts a parameter that is illustrated below:
- char: This parameter is a specified sequence of characters.
Return Value: This function will return true if the given string is present in the string otherwise it will return false.
Example 1:
Swift
import Foundation
let string = "GFG is a CS Portal."
let result1 = string. contains ( "CS" )
print (result1)
let result2 = string. contains ( "GeeksforGeeks" )
print (result2)
|
Output:
true
false
Example 2:
Swift
import Foundation
let string = "GFG is a CS Portal."
if (string. contains ( " " ))
{
print ( "Blank space is present in the string" )
}
else {
print ( "Blank space is not present in the string" )
}
if (string. contains ( "Computer Science" ))
{
print ( "Computer Science is present in the string" )
}
else {
print ( "Computer Science is not present in the string" )
}
|
Output:
Blank space is present in the string
Computer Science is not present in the string
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...