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

后端 未结 27 3673
天命终不由人
天命终不由人 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:26

    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 :)

提交回复
热议问题