Swift: String contains String (Without using NSString)?

后端 未结 4 1685
逝去的感伤
逝去的感伤 2020-12-19 02:16

I have the same problem like in this question:

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

But now a few months later I wonder if it can be

相关标签:
4条回答
  • 2020-12-19 02:48

    just to demonstrate the use of options.

    var string = "This is a test.  This is only a test. Not an Exam"
    
    if string.range(of:"ex") != nil {
        print("yes")
    }
    if string.range(of:"ex", options: String.CompareOptions.caseInsensitive) != nil {
        print("yes")
    }
    
    0 讨论(0)
  • 2020-12-19 02:50

    I wrote an extension on String for SWIFT 3.0 so that i could simply call absoluteString.contains(string: "/kredit/")

    extension String {
      public func contains(string: String)-> Bool {
          return self.rangeOfString(string) != nil
      }
    

    }

    0 讨论(0)
  • 2020-12-19 03:00

    String actually provides a "contains" function through StringProtocol.
    No extension whatsoever needed:

    let str = "asdf"
    print(str.contains("sd") ? "yep" : "nope")
    

    https://developer.apple.com/reference/swift/string https://developer.apple.com/documentation/swift/stringprotocol


    If you want to check if your string matches a specific pattern, I can recommend the NSHipster article about NSRegularExpressions: http://nshipster.com/nsregularexpression/

    0 讨论(0)
  • 2020-12-19 03:06

    Same way, just with Swift syntax:

    let string = "This is a test.  This is only a test"
    
    if string.rangeOfString("only") != nil {
         println("yes")
    }
    

    For Swift 3.0

    if str.range(of: "abc") != nil{
         print("Got the string")
    }
    
    0 讨论(0)
提交回复
热议问题