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

前端 未结 23 1753

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

    Please use this code

    NSString *string = @"hello bla bla";
    if ([string rangeOfString:@"bla"].location == NSNotFound) 
    {
        NSLog(@"string does not contain bla");
    } 
    else 
    {  
        NSLog(@"string contains bla!");
    }
    
    0 讨论(0)
  • 2020-11-22 15:23

    Here is a copy-and-paste function snippet:

    -(BOOL)Contains:(NSString *)StrSearchTerm on:(NSString *)StrText
    {
        return [StrText rangeOfString:StrSearchTerm 
            options:NSCaseInsensitiveSearch].location != NSNotFound;
    }
    
    0 讨论(0)
  • 2020-11-22 15:23

    In case of swift, this can be used

    let string = "Package #23"
    if string.containsString("Package #") {
        //String contains substring
    }
    else {
        //String does not contain substring
    }
    
    0 讨论(0)
  • 2020-11-22 15:24

    With iOS 8 and Swift, we can use localizedCaseInsensitiveContainsString method

     let string: NSString = "Café"
     let substring: NSString = "É"
    
     string.localizedCaseInsensitiveContainsString(substring) // true
    
    0 讨论(0)
  • 2020-11-22 15:24

    If you need this once write:

    NSString *stringToSearchThrough = @"-rangeOfString method finds and returns the range of the first occurrence of a given string within the receiver.";
    BOOL contains = [stringToSearchThrough rangeOfString:@"occurence of a given string"].location != NSNotFound;
    
    0 讨论(0)
提交回复
热议问题