iOS开发笔记——NSString详解

NSString

一、NSString截取

字符串第一位index0

1.从开头截取到指定位置(不包括该位置)

- (NSString *)substringToIndex:(NSUInteger)to;
NSString *str = @"abcdefg";
str = [str substringToIndex:3]; // abc

2.从字符串指定位置开始截取到最后 (包括该位置)

- (NSString *)substringFromIndex:(NSUInteger)from;
NSString *str = @"abcdefg";
str = [str substringFromIndex:3]; // defg

3.截取指定范围的字符串

- (NSString *)substringWithRange:(NSRange)range; 

typedef struct _NSRange {
    NSUInteger location;
    NSUInteger length;
} NSRange;

NSString *str = @"abcdefg";
str = [str substringWithRange:NSMakeRange(1, 2)]; // bc

二、NSString拼接

1.stringWithFormat

+ (instancetype)stringWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);

NSString *str = @"abcdefg";
NSString *str1 = @"123456";
str = [NSString stringWithFormat:@"%@%@",str,str1];
// abcdefg123456

2.stringByAppendingString

- (NSString *)stringByAppendingString:(NSString *)aString;
NSString *str = @"abcdefg";
NSString *str1 = @"123456";
str = [str stringByAppendingString:str1];

3 stringByAppendingFormat

- (NSString *)stringByAppendingFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
NSString *str = @"abcdefg";
NSString *str1 = @"123456";
str = [str stringByAppendingFormat:@"%@",str1];

三、NSString查询

1.查询是否以某字符串开头

NSString * string = @"abcdef";
NSString * str = @"abc";
BOOL isOrNot = [string hasPrefix:str];

2.查询是否以某字符串结尾

BOOL isOrNot = [string hasSuffix:str];

3.查询是否包含某字符串

NSRange range = [string rangeOfString:str];
NSLog(@"%ld, %ld", range.location, range.length);

4.NSString分割

NSString * string = @"abc|def";
NSArray * arr = [string componentsSeparatedByString:@"|"];
// abc,def

你可能感兴趣的:(iOS开发笔记——NSString详解)