Swift 3 String Contains Exact Sentence/Word

Swift 3 String Contains Exact Sentence / Word

A solution is Regular Expression which is able to check for word boundaries.

This is a simple String extension, the pattern searches for the query string wrapped in word boundaries (\b)

extension String {
func contains(word : String) -> Bool
{
do {
let regex = try NSRegularExpression(pattern: "\\b\(word)\\b")
return regex.numberOfMatches(in: self, range: NSRange(word.startIndex..., in: word)) > 0
} catch {
return false
}
}
}

Or – thanks to Sulthan – still simpler

extension String {
func contains(word : String) -> Bool
{
return self.range(of: "\\b\(word)\\b", options: .regularExpression) != nil
}
}

Usage:

let string = "I know your name"
string.contains(word:"your") // true
string.contains(word:"you") // false

How to get a String Contains number of Exact Sentence / Word in swift 4?


import Foundation

extension String {
func nazmulCount(of needle: String) -> Int {
let pattern = "\\b" + NSRegularExpression.escapedPattern(for: needle) + "\\b"
let rex = try! NSRegularExpression(pattern: pattern, options: [.caseInsensitive])
return rex.matches(in: self, options: [], range: NSRange(startIndex..., in: self)).count
}
}

"Art of swift, now art of swift5 but this is true art of swift from 2014 now what do you think about art of swift?".nazmulCount(of: "art of swift")
// 3

"Art of swift".nazmulCount(of: "art of swift")
// 1

"art of swift?".nazmulCount(of: "art of swift")
// 1

"art of swift's".nazmulCount(of: "art of swift")
// 1

"art of swiftবাং".nazmulCount(of: "art of swift")
// 0

"art of swiftly".nazmulCount(of: "art of swift")
// 0

Swift 4 contains method doesn't work truly for short words like as

You need to use a regular expression to make sure the word you're looking for has word boundaries on both sides (instead of other letters). Use:

if a.range(of: "\\bas\\b", options: [.regularExpression], range: (a.startIndex..<a.endIndex), locale: nil) != nil {

The regular expression keyword \\b is to match a word boundary.

How can I check if sentences in array contains exact words in Swift?

You need to move the print sentence out of your loop.

Like this:

var arr = [String]()

for review in reviews {
for word in words {
if review.containsString(word) {
arr.append(review)
}
}
}
print(arr)

Also, if you don't want to get duplicate reviews, I would use a set instead of an array: var arr = Set<String>()

Also, it's probably the case that you need a case insensitive string comparison. Change Food by food in your words array and try again.

To get a full case insensitive loop working, try this:

for review in reviews {
for word in words {
if review.lowercaseString.containsString(word.lowercaseString) {
arr.append(review)
}
}
}
print(arr)

How do I check if a string contains another string 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

  1. 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.

remove exact word phrase from string in Swift or Objective-C


// Convert string to array of words
let words = string.components(separatedBy: " ")

// Do the same for your search words
let wordsToRemove = "red horse".components(separatedBy: " ")

// remove only the full matching words, and reform the string
let result = words.filter { !wordsToRemove.contains($0) }.joined(separator: " ")

// result = "Did the favored win the race?"

The caveat to this method is that it will remove those exact words anywhere in your original string. If you want the result to only remove the words where they appear in that exact order, then just use a space at the front of the parameter for replacingOccurrencesOf.

Extract a name from a sentence

When you have rest of the text you can separate it by " ". Then first and secont elements are first and last name

let array = text.components(separatedBy: " ")

//first name
print(array[0])

//last name
print(array[1])


Related Topics



Leave a reply



Submit