iOS 字符串截取

1 /* To avoid breaking up character sequences such as Emoji, you can do:
2     [str substringFromIndex:[str rangeOfComposedCharacterSequenceAtIndex:index].location]
3     [str substringToIndex:NSMaxRange([str rangeOfComposedCharacterSequenceAtIndex:index])]
4     [str substringWithRange:[str rangeOfComposedCharacterSequencesForRange:range]
5 */
6 - (NSString *)substringFromIndex:(NSUInteger)from;
7 - (NSString *)substringToIndex:(NSUInteger)to;
8 - (NSString *)substringWithRange:(NSRange)range;                // Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up character sequences

1、通过下标获取字符串

1 NSString * str = @"12345abcde";
2 NSString *logStr = [str substringFromIndex:6]; //从字符串下标为 6 的开始,截止字符串末尾
1 NSString * str = @"12345abcde";
2 NSString *logStr = [str substringToIndex:3]; //从字符串开始,截止字符串下标为 3 
 1 /**
 2 typedef struct _NSRange {
 3     NSUInteger location;
 4     NSUInteger length;
 5 } NSRange;
 6 
 7 typedef NSRange *NSRangePointer;
 8 
 9 NS_INLINE NSRange NSMakeRange(NSUInteger loc, NSUInteger len) {
10     NSRange r;
11     r.location = loc;
12     r.length = len;
13     return r;
14 }
15 */
16 
17 NSString * str = @"12345abcde";
18 NSString *logStr = [str substringWithRange:NSMakeRange(2, 4)]; //从下标为2开始,截取长度为4的字符串

2、匹配查找字符串

1  NSString * str = @"12345abcde";
2  NSRange *logRange = [str rangeOfString:@"ab"]; //返回匹配到字符串的起始下标及长度

3、分割字符串

1 NSString * str = @"12345abcde";
2 NSArray *logArr = [str componentsSeparatedByString:@"a"]; //以a为分隔符,返回分割后的字符串数组
3 //数组元素拼接为字符串
4 NSString *toStr = [logArr componentsJoinedByString:@","];
5 //toStr  12345,bcde

 

iOS 字符串截取

上一篇:Android6.0+关机状态下实现充电自动开机


下一篇:drbd配置文件