Open In App

How to check if a string contains another string in Swift?

Last Updated : 05 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Swift program to check if the specified string
// is present in the string or not
import Foundation
  
// Creating an string
let string = "GFG is a CS Portal."
  
// Checking if the string contains "CS"
let result1 = string.contains("CS")
  
// Getting the result
print(result1)
  
// Checking if the string contains "GeeksforGeeks"
let result2 = string.contains("GeeksforGeeks")
  
// Getting the result
print(result2)


Output:

true
false

Example 2:

Swift




// Swift program to check if the specified string
// is present in the string or not
import Foundation
  
// Creating an string
let string = "GFG is a CS Portal."
  
// Checking if the given string is present in the string or not
if (string.contains(" "))
{
    print("Blank space is present in the string")
}
else{
    print("Blank space is not present in the string")
}
    
// Checking if the given string is present in 
// the string or not
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
Previous
Next
Share your thoughts in the comments

Similar Reads