0

I have a array with some words and I want to check whether these words exist in my string or not. Here is the sample code

var array: NSArray = ["one", "two", "three", "four"]

var Str: NSString = "one example of my string"

Now one exist in the string, but I am not able to compare them. How to get that one compared?

1
  • check the arraycontains method . Commented Mar 28, 2016 at 11:37

4 Answers 4

1

Do it like this,

var array: NSArray = ["one", "two", "three", "four"]

var Str: NSString = "one example of my string"

let filteredString = Str.componentsSeparatedByString(" ").filter { a in
    return array.containsObject(a)
}
print(filteredString)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the NSString.containsString(string) method:

let Str : NSString = "This is one string"
let array : [NSString] = ["one", "two", "three", "four"]

for word in array {
    print("is \(word) mentioned in string? : \(Str.containsString(word as String))" )
}

with output:

  • is one mentioned in string? : true
  • is two mentioned in string? : false
  • is three mentioned in string? : false
  • is four mentioned in string? : false

Comments

0

To use a method if you have different arrays of strings to check you can do it like that:

var array: NSArray = ["one", "two", "three", "four"]

var str: NSString = "one example of my string"

func checkIfStringOfArrayExists(arrayOfString: NSArray, inString string: NSString) -> Bool {
    for element in array where str.containsString(element as! String) {
        return true
    }
    return false
}

checkIfStringOfArrayExists(array, inString: str) // true

1 Comment

Thanks, I find this option an easy one. Because I can do my stuff now.
0

If simple Bool result is what you need:

array.contains{ string.containsString(String($0)) } // true

However, I would suggest working with Swift's Array and String value types instead and then extending String as follows:

public extension String {

    public func containsAny(strings: [String]) -> Bool {
        return strings.contains{ containsString($0) }
    }
}

let strings = ["one", "two", "three", "four"]
let string = "one example of my string"

string.containsAny(strings) // true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.