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

后端 未结 27 3829
天命终不由人
天命终不由人 2020-11-22 12:32

In Objective-C the code to check for a substring in an NSString is:

NSString *string = @\"hello Swift\";
NSRange textRange =[strin         


        
27条回答
  •  星月不相逢
    2020-11-22 13:15

    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;

提交回复
热议问题