Swift instr or strpos Equivalent - swift

I've searched and searched but can't see to find what the instr or strpos equivalent in Swift is. Just need to see if a string contains a string. How can I do this in Swift?

Here is a useful extension of String in Swift. Both functions work like the well known PHP functions. Just paste this code in any .swift file of your project:
import Foundation
extension String {
func strpos(needle:String)->Int{
//Returns the index of the first occurrence of a substring in a string, or -1 if absent
if let range = self.rangeOfString(needle) {
return startIndex.distanceTo(range.startIndex)
} else {
return -1
}
}
func instr(needle:String)->Bool{
return self.containsString(needle)
}
}
Usage, anywhere else in your projet
let myString = "Hello, world"
print(myString.strpos("world")) //->prints "7"
print(myString.strpos("Dolly")) //->prints "-1"
print(myString.strpos(",")) //->prints "5"

Use rangOfString():
if string.rangeOfString("mySubstring") != nil
{
println("string contains substring")
}

Related

How to fix deprecated substring(with: )

I'm working through a book exercise where the author has the following code.
func getMatchingString(str: String) -> String? {
if let newMatch = str.range(of:regExFindMatchString,
options:.regularExpression) {
return str.substring(with: newMatch)
} else {
return nil
}
}
the str.substring(with: newMatch) line shows 'substring(with:) is deprecated use String slicing subscript.'
I've tried to figure out what to use to fix this but everything I've tried shows I just don't understand this well enough to fix it. I know that the newMatch is a range object, just can't figure out how to use it effectively.
Any help is greatly appreciated..
Bob
Just use subscripting with the range you obtain from the if let
if let newMatchRange = str.range(of:regExFindMatchString, options:.regularExpression) {
return String(str[newMatchRange])
} else {
return nil
}
You need to translate it to a String as the method actually returns a Substring type, not a String.

Trim only trailing whitespace from end of string in Swift 3

Every example of trimming strings in Swift remove both leading and trailing whitespace, but how can only trailing whitespace be removed?
For example, if I have a string:
" example "
How can I end up with:
" example"
Every solution I've found shows trimmingCharacters(in: CharacterSet.whitespaces), but I want to retain the leading whitespace.
RegEx is a possibility, or a range can be derived to determine index of characters to remove, but I can't seem to find an elegant solution for this.
With regular expressions:
let string = " example "
let trimmed = string.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression)
print(">" + trimmed + "<")
// > example<
\s+ matches one or more whitespace characters, and $ matches
the end of the string.
In Swift 4 & Swift 5
This code will also remove trailing new lines.
It works based on a Character struct's method .isWhitespace
var trailingSpacesTrimmed: String {
var newString = self
while newString.last?.isWhitespace == true {
newString = String(newString.dropLast())
}
return newString
}
This short Swift 3 extension of string uses the .anchored and .backwards option of rangeOfCharacter and then calls itself recursively if it needs to loop. Because the compiler is expecting a CharacterSet as the parameter, you can just supply the static when calling, e.g. "1234 ".trailing(.whitespaces) will return "1234". (I've not done timings, but would expect faster than regex.)
extension String {
func trailingTrim(_ characterSet : CharacterSet) -> String {
if let range = rangeOfCharacter(from: characterSet, options: [.anchored, .backwards]) {
return self.substring(to: range.lowerBound).trailingTrim(characterSet)
}
return self
}
}
In Foundation you can get ranges of indices matching a regular expression. You can also replace subranges. Combining this, we get:
import Foundation
extension String {
func trimTrailingWhitespace() -> String {
if let trailingWs = self.range(of: "\\s+$", options: .regularExpression) {
return self.replacingCharacters(in: trailingWs, with: "")
} else {
return self
}
}
}
You can also have a mutating version of this:
import Foundation
extension String {
mutating func trimTrailingWhitespace() {
if let trailingWs = self.range(of: "\\s+$", options: .regularExpression) {
self.replaceSubrange(trailingWs, with: "")
}
}
}
If we match against \s* (as Martin R. did at first) we can skip the if let guard and force-unwrap the optional since there will always be a match. I think this is nicer since it's obviously safe, and remains safe if you change the regexp. I did not think about performance.
Handy String extension In Swift 4
extension String {
func trimmingTrailingSpaces() -> String {
var t = self
while t.hasSuffix(" ") {
t = "" + t.dropLast()
}
return t
}
mutating func trimmedTrailingSpaces() {
self = self.trimmingTrailingSpaces()
}
}
Swift 4
extension String {
var trimmingTrailingSpaces: String {
if let range = rangeOfCharacter(from: .whitespacesAndNewlines, options: [.anchored, .backwards]) {
return String(self[..<range.lowerBound]).trimmingTrailingSpaces
}
return self
}
}
Demosthese's answer is a useful solution to the problem, but it's not particularly efficient. This is an upgrade to their answer, extending StringProtocol instead, and utilizing Substring to remove the need for repeated copying.
extension StringProtocol {
#inline(__always)
var trailingSpacesTrimmed: Self.SubSequence {
var view = self[...]
while view.last?.isWhitespace == true {
view = view.dropLast()
}
return view
}
}
No need to create a new string when dropping from the end each time.
extension String {
func trimRight() -> String {
String(reversed().drop { $0.isWhitespace }.reversed())
}
}
This operates on the collection and only converts the result back into a string once.
It's a little bit hacky :D
let message = " example "
var trimmed = ("s" + message).trimmingCharacters(in: .whitespacesAndNewlines)
trimmed = trimmed.substring(from: trimmed.index(after: trimmed.startIndex))
Without regular expression there is not direct way to achieve that.Alternatively you can use the below function to achieve your required result :
func removeTrailingSpaces(with spaces : String) -> String{
var spaceCount = 0
for characters in spaces.characters{
if characters == " "{
print("Space Encountered")
spaceCount = spaceCount + 1
}else{
break;
}
}
var finalString = ""
let duplicateString = spaces.replacingOccurrences(of: " ", with: "")
while spaceCount != 0 {
finalString = finalString + " "
spaceCount = spaceCount - 1
}
return (finalString + duplicateString)
}
You can use this function by following way :-
let str = " Himanshu "
print(removeTrailingSpaces(with : str))
One line solution with Swift 4 & 5
As a beginner in Swift and iOS programming I really like #demosthese's solution above with the while loop as it's very easy to understand. However the example code seems longer than necessary. The following uses essentially the same logic but implements it as a single line while loop.
// Remove trailing spaces from myString
while myString.last == " " { myString = String(myString.dropLast()) }
This can also be written using the .isWhitespace property, as in #demosthese's solution, as follows:
while myString.last?.isWhitespace == true { myString = String(myString.dropLast()) }
This has the benefit (or disadvantage, depending on your point of view) that this removes all types of whitespace, not just spaces but (according to Apple docs) also including newlines, and specifically the following characters:
“\t” (U+0009 CHARACTER TABULATION)
“ “ (U+0020 SPACE)
U+2029 PARAGRAPH SEPARATOR
U+3000 IDEOGRAPHIC SPACE
Note: Even though .isWhitespace is a Boolean it can't be used directly in the while loop as it ends up being optional ? due to the chaining of the optional .last property, which returns nil if the String (or collection) is empty. The == true logic gets around this since nil != true.
I'd love to get some feedback on this, esp. in case anyone sees any issues or drawbacks with this simple single line approach.
Swift 5
extension String {
func trimTrailingWhiteSpace() -> String {
guard self.last == " " else { return self }
var tmp = self
repeat {
tmp = String(tmp.dropLast())
} while tmp.last == " "
return tmp
}
}

How can I check if a string contains Chinese in Swift?

I want to know that how can I check if a string contains Chinese in Swift?
For example, I want to check if there's Chinese inside:
var myString = "Hi! 大家好!It's contains Chinese!"
Thanks!
This answer
to How to determine if a character is a Chinese character can also easily be translated from
Ruby to Swift (now updated for Swift 3):
extension String {
var containsChineseCharacters: Bool {
return self.range(of: "\\p{Han}", options: .regularExpression) != nil
}
}
if myString.containsChineseCharacters {
print("Contains Chinese")
}
In a regular expression, "\p{Han}" matches all characters with the
"Han" Unicode property, which – as I understand it – are the characters
from the CJK languages.
Looking at questions on how to do this in other languages (such as this accepted answer for Ruby) it looks like the common technique is to determine if each character in the string falls in the CJK range. The ruby answer could be adapted to Swift strings as extension with the following code:
extension String {
var containsChineseCharacters: Bool {
return self.unicodeScalars.contains { scalar in
let cjkRanges: [ClosedInterval<UInt32>] = [
0x4E00...0x9FFF, // main block
0x3400...0x4DBF, // extended block A
0x20000...0x2A6DF, // extended block B
0x2A700...0x2B73F, // extended block C
]
return cjkRanges.contains { $0.contains(scalar.value) }
}
}
}
// true:
"Hi! 大家好!It's contains Chinese!".containsChineseCharacters
// false:
"Hello, world!".containsChineseCharacters
The ranges may already exist in Foundation somewhere rather than manually hardcoding them.
The above is for Swift 2.0, for earlier, you will have to use the free contains function rather than the protocol extension (twice):
extension String {
var containsChineseCharacters: Bool {
return contains(self.unicodeScalars) {
// older version of compiler seems to need extra help with type inference
(scalar: UnicodeScalar)->Bool in
let cjkRanges: [ClosedInterval<UInt32>] = [
0x4E00...0x9FFF, // main block
0x3400...0x4DBF, // extended block A
0x20000...0x2A6DF, // extended block B
0x2A700...0x2B73F, // extended block C
]
return contains(cjkRanges) { $0.contains(scalar.value) }
}
}
}
The accepted answer only find if string contains Chinese character, i created one suit for my own case:
enum ChineseRange {
case notFound, contain, all
}
extension String {
var findChineseCharacters: ChineseRange {
guard let a = self.range(of: "\\p{Han}*\\p{Han}", options: .regularExpression) else {
return .notFound
}
var result: ChineseRange
switch a {
case nil:
result = .notFound
case self.startIndex..<self.endIndex:
result = .all
default:
result = .contain
}
return result
}
}
if "你好".findChineseCharacters == .all {
print("All Chinese")
}
if "Chinese".findChineseCharacters == .notFound {
print("Not found Chinese")
}
if "Chinese你好".findChineseCharacters == .contain {
print("Contains Chinese")
}
gist here: https://gist.github.com/williamhqs/6899691b5a26272550578601bee17f1a
Try this in Swift 2:
var myString = "Hi! 大家好!It's contains Chinese!"
var a = false
for c in myString.characters {
let cs = String(c)
a = a || (cs != cs.stringByApplyingTransform(NSStringTransformMandarinToLatin, reverse: false))
}
print("\(myString) contains Chinese characters = \(a)")
I have created a Swift 3 String extension for checking how much Chinese characters a String contains. Similar to the code by Airspeed Velocity but more comprehensive. Checking various Unicode ranges to see whether a character is Chinese. See Chinese character ranges listed in the tables under section 18.1 in the Unicode standard specification: http://www.unicode.org/versions/Unicode9.0.0/ch18.pdf
The String extension can be found on GitHub: https://github.com/niklasberglund/String-chinese.swift
Usage example:
let myString = "Hi! 大家好!It contains Chinese!"
let chinesePercentage = myString.chinesePercentage()
let chineseCharacterCount = myString.chineseCharactersCount()
print("String contains \(chinesePercentage) percent Chinese. That's \(chineseCharacterCount) characters.")

How can I check if a string contains letters in Swift? [duplicate]

This question already has answers here:
What is the best way to determine if a string contains a character from a set in Swift
(11 answers)
Closed 7 years ago.
I'm trying to check whether a specific string contains letters or not.
So far I've come across NSCharacterSet.letterCharacterSet() as a set of letters, but I'm having trouble checking whether a character in that set is in the given string. When I use this code, I get an error stating:
'Character' is not convertible to 'unichar'
For the following code:
for chr in input{
if letterSet.characterIsMember(chr){
return "Woah, chill out!"
}
}
You can use NSCharacterSet in the following way :
let letters = NSCharacterSet.letters
let phrase = "Test case"
let range = phrase.rangeOfCharacter(from: characterSet)
// range will be nil if no letters is found
if let test = range {
println("letters found")
}
else {
println("letters not found")
}
Or you can do this too :
func containsOnlyLetters(input: String) -> Bool {
for chr in input {
if (!(chr >= "a" && chr <= "z") && !(chr >= "A" && chr <= "Z") ) {
return false
}
}
return true
}
In Swift 2:
func containsOnlyLetters(input: String) -> Bool {
for chr in input.characters {
if (!(chr >= "a" && chr <= "z") && !(chr >= "A" && chr <= "Z") ) {
return false
}
}
return true
}
It's up to you, choose a way. I hope this help you.
You should use the Strings built in range functions with NSCharacterSet rather than roll your own solution. This will give you a lot more flexibility too (like case insensitive search if you so desire).
let str = "Hey this is a string"
let characterSet = NSCharacterSet(charactersInString: "aeiou")
if let _ = str.rangeOfCharacterFromSet(characterSet, options: .CaseInsensitiveSearch) {
println("true")
}
else {
println("false")
}
Substitute "aeiou" with whatever letters you're looking for.
A less flexible, but fun swift note all the same, is that you can use any of the functions available for Sequences. So you can do this:
contains("abc", "c")
This of course will only work for individual characters, and is not flexible and not recommended.
The trouble with .characterIsMember is that it takes a unichar (a typealias for UInt16).
If you iterate your input using the utf16 view of the string, it will work:
let set = NSCharacterSet.letterCharacterSet()
for chr in input.utf16 {
if set.characterIsMember(chr) {
println("\(chr) is a letter")
}
}
You can also skip the loop and use the contains algorithm if you only want to check for presence/non-presence:
if contains(input.utf16, { set.characterIsMember($0) }) {
println("contains letters")
}

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

In Objective-C the code to check for a substring in an NSString is:
NSString *string = #"hello Swift";
NSRange textRange =[string rangeOfString:#"Swift"];
if(textRange.location != NSNotFound)
{
NSLog(#"exists");
}
But how do I do this in Swift?
You can do exactly the same call with Swift:
Swift 4 & Swift 5
In Swift 4 String is a collection of Character values, it wasn't like this in Swift 2 and 3, so you can use this more concise code1:
let string = "hello Swift"
if string.contains("Swift") {
print("exists")
}
Swift 3.0+
var string = "hello Swift"
if string.range(of:"Swift") != nil {
print("exists")
}
// alternative: not case sensitive
if string.lowercased().range(of:"swift") != nil {
print("exists")
}
Older Swift
var string = "hello Swift"
if string.rangeOfString("Swift") != nil{
println("exists")
}
// alternative: not case sensitive
if string.lowercaseString.rangeOfString("swift") != nil {
println("exists")
}
I hope this is a helpful solution since some people, including me, encountered some strange problems by calling containsString().1
PS. Don't forget to import Foundation
Footnotes
Just remember that using collection functions on Strings has some edge cases which can give you unexpected results, e. g. when dealing with emojis or other grapheme clusters like accented letters.
Extension way
Swift 4
extension String {
func contains(find: String) -> Bool{
return self.range(of: find) != nil
}
func containsIgnoringCase(find: String) -> Bool{
return self.range(of: find, options: .caseInsensitive) != nil
}
}
var value = "Hello world"
print(value.contains("Hello")) // true
print(value.contains("bo")) // false
print(value.containsIgnoringCase(find: "hello")) // true
print(value.containsIgnoringCase(find: "Hello")) // true
print(value.containsIgnoringCase(find: "bo")) // false
Generally Swift 4 has contains method however it available from iOS 8.0+
Swift 3.1
You can write extension contains: and containsIgnoringCase for String
extension String {
func contains(_ find: String) -> Bool{
return self.range(of: find) != nil
}
func containsIgnoringCase(_ find: String) -> Bool{
return self.range(of: find, options: .caseInsensitive) != nil
}
}
Older Swift version
extension String {
func contains(find: String) -> Bool{
return self.rangeOfString(find) != nil
}
func containsIgnoringCase(find: String) -> Bool{
return self.rangeOfString(find, options: NSStringCompareOptions.CaseInsensitiveSearch) != nil
}
}
Example:
var value = "Hello world"
print(value.contains("Hello")) // true
print(value.contains("bo")) // false
print(value.containsIgnoringCase("hello")) // true
print(value.containsIgnoringCase("Hello")) // true
print(value.containsIgnoringCase("bo")) // false
From the docs, it seems that calling containsString() on a String should work:
Swift’s String type is bridged seamlessly to Foundation’s NSString
class. If you are working with the Foundation framework in Cocoa or
Cocoa Touch, the entire NSString API is available to call on any
String value you create, in addition to the String features described
in this chapter. You can also use a String value with any API that
requires an NSString instance.
However, it doesn't seem to work that way.
If you try to use someString.containsString(anotherString), you will get a compile time error that states 'String' does not contain a member named 'containsString'.
So, you're left with a few options, one of which is to explicitly bridge your String to Objective-C by using bridgeToObjectiveC() other two involve explicitly using an NSString and the final one involves casting the String to an NSString
By bridging, you'd get:
var string = "hello Swift"
if string.bridgeToObjectiveC().containsString("Swift") {
println("YES")
}
By explicitly typing the string as an NSString, you'd get:
var string: NSString = "hello Swift"
if string.containsString("Swift") {
println("YES")
}
If you have an existing String, you can initialize an NSString from it by using NSString(string:):
var string = "hello Swift"
if NSString(string: string).containsString("Swift") {
println("YES")
}
And finally, you can cast an existing String to an NSString as below
var string = "hello Swift"
if (string as NSString).containsString("Swift") {
println("YES")
}
Another one. Supports case and diacritic options.
Swift 3.0
struct MyString {
static func contains(_ text: String, substring: String,
ignoreCase: Bool = true,
ignoreDiacritic: Bool = true) -> Bool {
var options = NSString.CompareOptions()
if ignoreCase { _ = options.insert(NSString.CompareOptions.caseInsensitive) }
if ignoreDiacritic { _ = options.insert(NSString.CompareOptions.diacriticInsensitive) }
return text.range(of: substring, options: options) != nil
}
}
Usage
MyString.contains("Niels Bohr", substring: "Bohr") // true
iOS 9+
Case and diacritic insensitive function available since iOS 9.
if #available(iOS 9.0, *) {
"Für Elise".localizedStandardContains("fur") // true
}
As of Xcode 7.1 and Swift 2.1 containsString() is working fine for me.
let string = "hello swift"
if string.containsString("swift") {
print("found swift")
}
Swift 4:
let string = "hello swift"
if string.contains("swift") {
print("found swift")
}
And a case insensitive Swift 4 example:
let string = "Hello Swift"
if string.lowercased().contains("swift") {
print("found swift")
}
Or using a case insensitive String extension:
extension String {
func containsIgnoreCase(_ string: String) -> Bool {
return self.lowercased().contains(string.lowercased())
}
}
let string = "Hello Swift"
let stringToFind = "SWIFT"
if string.containsIgnoreCase(stringToFind) {
print("found: \(stringToFind)") // found: SWIFT
}
print("string: \(string)")
print("stringToFind: \(stringToFind)")
// console output:
found: SWIFT
string: Hello Swift
stringToFind: SWIFT
In Swift 4.2
Use
func contains(_ str: String) -> Bool
Example
let string = "hello Swift"
let containsSwift = string.contains("Swift")
print(containsSwift) // prints true
> IN SWIFT 3.0
let str = "Hello Swift"
if str.lowercased().contains("Swift".lowercased()) {
print("String Contains Another String")
} else {
print("Not Exists")
}
Output
String Contains Another String
You can do this very easily in Swift using the code:
let string = "hello Swift";
let subString = (string as NSString).containsString("Swift")
if(subString){println("Exist")}
Of all of the answers here, I think they either don't work, or they're a bit of a hack (casting back to NSString). It's very likely that the correct answer to this has changed with the different beta releases.
Here is what I use:
let string: String = "hello Swift"
if string.rangeOfString("Swift") != nil
{
println("exists")
}
The "!= nil" became required with Beta 5.
Just an addendum to the answers here.
You can also do a local case insensitive test using:
- (BOOL)localizedCaseInsensitiveContainsString:(NSString *)aString
Example:
import Foundation
var string: NSString = "hello Swift"
if string.localizedCaseInsensitiveContainsString("Hello") {
println("TRUE")
}
UPDATE
This is part of the Foundation Framework for iOS & Mac OS X 10.10.x
and was part of 10.10 at Time of my original Posting.
Document Generated: 2014-06-05 12:26:27 -0700 OS X Release Notes
Copyright © 2014 Apple Inc. All Rights Reserved.
OS X 10.10 Release Notes Cocoa Foundation Framework
NSString now has the following two convenience methods:
- (BOOL)containsString:(NSString *)str;
- (BOOL)localizedCaseInsensitiveContainsString:(NSString *)str;
Here is my first stab at this in the swift playground.
I extend String by providing two new functions (contains and containsIgnoreCase)
extension String {
func contains(other: String) -> Bool{
var start = startIndex
do{
var subString = self[Range(start: start++, end: endIndex)]
if subString.hasPrefix(other){
return true
}
}while start != endIndex
return false
}
func containsIgnoreCase(other: String) -> Bool{
var start = startIndex
do{
var subString = self[Range(start: start++, end: endIndex)].lowercaseString
if subString.hasPrefix(other.lowercaseString){
return true
}
}while start != endIndex
return false
}
}
Use it like this
var sentence = "This is a test sentence"
sentence.contains("this") //returns false
sentence.contains("This") //returns true
sentence.containsIgnoreCase("this") //returns true
"This is another test sentence".contains(" test ") //returns true
I'd welcome any feedback :)
Here you are:
let s = "hello Swift"
if let textRange = s.rangeOfString("Swift") {
NSLog("exists")
}
You can just do what you have mentioned:
import Foundation
...
string.contains("Swift");
From the docs:
Swift’s String type is bridged seamlessly to Foundation’s NSString
class. If you are working with the Foundation framework in Cocoa or
Cocoa Touch, the entire NSString API is available to call on any
String value you create, in addition to the String features described
in this chapter. You can also use a String value with any API that
requires an NSString instance.
You need to import Foundation to bridge the NSString methods and make them available to Swift's String class.
You don't need to write any custom code for this. Starting from the 1.2 version Swift has already had all the methods you need:
getting string length: count(string);
checking if string contains substring: contains(string, substring);
checking if string starts with substring: startsWith(string, substring)
and etc.
In Swift 3
if((a.range(of: b!, options: String.CompareOptions.caseInsensitive, range: nil, locale: nil)) != nil){
print("Done")
}
Here you go! Ready for Xcode 8 and Swift 3.
import UIKit
let mString = "This is a String that contains something to search."
let stringToSearchUpperCase = "String"
let stringToSearchLowerCase = "string"
mString.contains(stringToSearchUpperCase) //true
mString.contains(stringToSearchLowerCase) //false
mString.lowercased().contains(stringToSearchUpperCase) //false
mString.lowercased().contains(stringToSearchLowerCase) //true
string.containsString is only available in 10.10 Yosemite (and probably iOS8).
Also bridging it to ObjectiveC crashes in 10.9. You're trying to pass a NSString to NSCFString. I don't know the difference, but I can say 10.9 barfs when it executes this code in a OS X 10.9 app.
Here are the differences in Swift with 10.9 and 10.10:
https://developer.apple.com/library/prerelease/mac/documentation/General/Reference/APIDiffsMacOSX10_10SeedDiff/index.html containsString is only available in 10.10
Range of String above works great on 10.9. I am finding developing on 10.9 is super stable with Xcode beta2. I don't use playgrounds through or the command line version of playgrounds. I'm finding if the proper frameworks are imported the autocomplete is very helpful.
Xcode 8/Swift 3 version:
let string = "hello Swift"
if let range = string.range(of: "Swift") {
print("exists at range \(range)")
} else {
print("does not exist")
}
if let lowercaseRange = string.lowercased().range(of: "swift") {
print("exists at range \(lowercaseRange)")
} else {
print("does not exist")
}
You can also use contains:
string.contains("swift") // false
string.contains("Swift") // true
Swift 4 way to check for substrings, including the necessary Foundation (or UIKit) framework import:
import Foundation // or UIKit
let str = "Oh Canada!"
str.contains("Can") // returns true
str.contains("can") // returns false
str.lowercased().contains("can") // case-insensitive, returns true
Unless Foundation (or UIKit) framework is imported, str.contains("Can") will give a compiler error.
This answer is regurgitating manojlds's answer, which is completely correct. I have no idea why so many answers go through so much trouble to recreate Foundation's String.contains(subString: String) method.
With and new syntax in swift 4 you can just
string.contains("Swift 4 is the best")
string is your string variable
Check if it contains 'Hello'
let s = "Hello World"
if s.rangeOfString("Hello") != nil {
print("Yes it contains 'Hello'")
}
Swift 5, case insensitive:
if string.localizedLowercase.contains("swift".localizedLowercase){
// Search string exist in employee name finding.
var empName:NSString! = employeeDetails[filterKeyString] as NSString
Case sensitve search.
let rangeOfSearchString:NSRange! = empName.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch)
// Not found.
if rangeOfSearchString.location != Foundation.NSNotFound
{
// search string not found in employee name.
}
// Found
else
{
// search string found in employee name.
}
Swift 3: Here you can see my smart search extension fro string that let you make a search on string for seeing if it contains, or maybe to filter a collection based on a search text.
https://github.com/magonicolas/Swift-Smart-String-Search
If you want to check that one String contains another Sub-String within it or not you can check it like this too,
var name = String()
name = "John has two apples."
Now, in this particular string if you want to know if it contains fruit name 'apple' or not you can do,
if name.contains("apple") {
print("Yes , it contains fruit name")
} else {
print("it does not contain any fruit name")
}
Hope this works for you.
In iOS 8 and newer, you can use these two NSString methods:
#availability(iOS, introduced=8.0)
func containsString(aString: String) -> Bool
#availability(iOS, introduced=8.0)
func localizedCaseInsensitiveContainsString(aString: String) -> Bool
I've found a couple of interesting use cases. These variants make use of the rangeOfString method and I include the equality example to show how one might best use the search and comparison features of Strings in Swift 2.0
//In viewDidLoad() I assign the current object description (A Swift String) to self.loadedObjectDescription
self.loadedObjectDescription = self.myObject!.description
Later after I've made changes to self.myObject, I can refer to the
following string comparison routines (setup as lazy variables that
return a Bool). This allows one to check the state at any time.
lazy var objectHasChanges : Bool = {
guard self.myObject != nil else { return false }
return !(self.loadedObjectDescription == self.myObject!.description)
}()
A variant of this happens when sometimes I need to analyze a missing
property on that object. A string search allows me to find a
particular substring being set to nil (the default when an object is created).
lazy var isMissingProperty : Bool = {
guard self.myObject != nil else { return true }
let emptyPropertyValue = "myProperty = nil"
return (self.myObject!.description.rangeOfString(emptyPropertyValue) != nil) ? true : false
}()
SWIFT 4 is very easy!!
if (yourString.contains("anyThing")) {
print("Exist")
}