NSString indexOf in Objective-C

前端 未结 4 781
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-28 11:31

Is there anything similar to an indexOf function in the NSString objects?

相关标签:
4条回答
  • 2020-12-28 12:07

    I know it's late, but I added a category that implements this method and many others similar to javascript string methods
    https://github.com/williamFalcon/WF-iOS-Categories

    0 讨论(0)
  • 2020-12-28 12:09

    Use -[NSString rangeOfString:]:

    - (NSRange)rangeOfString:(NSString *)aString;
    

    Finds and returns the range of the first occurrence of a given string within the receiver.

    0 讨论(0)
  • 2020-12-28 12:11

    If you want just know when String a contains String b use my way to do this.

    #define contains(str1, str2) ([str1 rangeOfString: str2 ].location != NSNotFound)
    
    //using 
    NSString a = @"PUC MINAS - BRAZIL";
    
    NSString b = @"BRAZIL";
    
    if( contains(a,b) ){
        //TO DO HERE
    }
    

    This is less readable but improves performance

    0 讨论(0)
  • 2020-12-28 12:31

    I wrote a category to extend original NSString object. Maybe you guys can reference it. (You also can see the article in my blog too.)

    ExtendNSString.h:

    #import <Foundation/Foundation.h>
    
    @interface NSString (util)
    
    - (int) indexOf:(NSString *)text;
    
    @end
    

    ExtendNSStriing.m:

    #import "ExtendNSString.h"
    
    @implementation NSString (util)
    
    - (int) indexOf:(NSString *)text {
        NSRange range = [self rangeOfString:text];
        if ( range.length > 0 ) {
            return range.location;
        } else {
            return -1;
        }
    }
    
    @end
    
    0 讨论(0)
提交回复
热议问题