NSString的几个常用接口

来源:互联网 发布:如何投诉网络运营商 编辑:程序博客网 时间:2024/05/26 17:47

NSString类需要掌握以下几个接口:


初始化:

- (instancetype)initWithString:(NSString *)aString

- (instancetype)initWithFormat:(NSString *)format...

+ (instancetype)stringWithString:(NSString *)aString

+ (instancetype)stringWithFormat:(NSString *)format...

        NSString *str1 = @"hello world.";                NSString *str2 = [[NSString alloc] initWithString:str1];        NSString *str3 = [NSString stringWithString:str1];                NSString *str4 = [[NSString alloc] initWithFormat: @"hello %@%c", @"world",'.'];        NSString *str5 = [NSString stringWithFormat: @"hello %@%c", @"world", '.'];                NSLog(@"str1 is %@", str1);        NSLog(@"str2 is %@", str2);        NSLog(@"str3 is %@", str3);        NSLog(@"str4 is %@", str4);        NSLog(@"str5 is %@", str5);
输出:

2015-10-30 22:21:57.896 testNSMutableString[563:14563] str1 is hello world.2015-10-30 22:21:57.897 testNSMutableString[563:14563] str2 is hello world.2015-10-30 22:21:57.897 testNSMutableString[563:14563] str3 is hello world.2015-10-30 22:21:57.898 testNSMutableString[563:14563] str4 is hello world.2015-10-30 22:21:57.898 testNSMutableString[563:14563] str5 is hello world.

比较:

- (BOOL)isEqualToString:(NSString *)aString

- (NSComparisonResult)compare:(NSString *)aString

        NSString *str6 = @"hello";        BOOL ret = [str1 isEqualToString:str6];        NSLog(@"ret is %d.", ret);        ret = [str1 isEqualToString:str2];        NSLog(@"ret is %d.", ret);                NSComparisonResult result = [str1 compare: str6];        if (result == NSOrderedSame)        {            NSLog(@"str1 = str6");        }        else if (result == NSOrderedAscending)        {            NSLog(@"str1 < str6");        }        else        {            NSLog(@"str1 > str6");        }

输出:

2015-10-30 22:33:15.461 testNSMutableString[622:18701] ret is 0.2015-10-30 22:33:15.461 testNSMutableString[622:18701] ret is 1.2015-10-30 22:33:15.461 testNSMutableString[622:18701] str1 > str6

子字符串:

- (NSString *)substringToIndex:(NSUInteger)anIndex

- (NSString *)substringFromIndex:(NSUInteger)anIndex

- (NSString *)substringWithRange:(NSRange)aRange

        NSString *str7 = [str2 substringFromIndex:2];        NSString *str8 = [str2 substringToIndex:2];        NSString *str9 = [str2 substringWithRange: NSMakeRange(2, 6)];        NSLog(@"str7 is %@", str7);        NSLog(@"str8 is %@", str8);        NSLog(@"str9 is %@", str9);

输出:

2015-10-30 22:37:34.464 testNSMutableString[638:20089] str7 is llo world.2015-10-30 22:37:34.464 testNSMutableString[638:20089] str8 is he2015-10-30 22:37:34.464 testNSMutableString[638:20089] str9 is llo wo


来源:

https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html#//apple_ref/occ/instm/NSString

0 0