Check if a string contains special character in it in Swift
In this tutorial, we will learn how to check if a string contains special characters in it in Swift with a simple example. If you want to check if your string is having any special characters except alphabets and digits then you will find a solution for that here.
Here we are going to check if a given string is containing special characters or not and the same can be done to find the alphabets and digits in the given string.
Is a string containing any special characters in it in swift!!
Firstly, to check whether a string contains any special character in it, we have to consider a string with special character(s) in it. So let us consider such string as,
let string = "Hello, world! #"
Then state the special characters that we have to check in the given string as,
let specialChars = (charactersIn: "!@#$%^&*()_+-=[]{}|;':\",./<>?\\")
Then for searching the special characters in string we have to provide the range of character in the string as,
if let _ = string.rangeOfCharacter(from: specialChars){ print("The string contains at least one special character") } else { print("The string does not contain any special characters") }
After providing the range of character in the string we are giving “if else” condition by which we will get output as “The string contains at least one special character” if any special character is present in the string otherwise it will print “The string does not contain any special character”.
Then the whole characters in the string are checked and finally, we get the output as follows,
OUTPUT:
The string contains at least one special character
Leave a Reply