How do I check if a string contains another string in Objective-C?

前端 未结 23 1743

How can I check if a string (NSString) contains another smaller string?

I was hoping for something like:

NSString *string = @\"hello bla         


        
23条回答
  •  囚心锁ツ
    2020-11-22 15:20

    For iOS 8.0+ and macOS 10.10+, you can use NSString's native containsString:.

    For older versions of iOS and macOS, you can create your own (obsolete) category for NSString:

    @interface NSString ( SubstringSearch )
        - (BOOL)containsString:(NSString *)substring;
    @end
    
    // - - - - 
    
    @implementation NSString ( SubstringSearch )
    
    - (BOOL)containsString:(NSString *)substring
    {    
        NSRange range = [self rangeOfString : substring];
        BOOL found = ( range.location != NSNotFound );
        return found;
    }
    
    @end
    

    Note: Observe Daniel Galasko's comment below regarding naming

提交回复
热议问题