闻道丶iOS(尝鲜版)iOS Developer

字符串转数组

2017-03-27  本文已影响338人  吃蘑菇De大灰狼

含有分隔符

将string字符串转换为array数组

 NSArray  *array = [str componentsSeparatedByString:@","];--分隔符

将array数组转换为string字符串

 NSString *str = [array componentsJoinedByString:@","];--分隔符

不含有分隔符

NSString * str = @"hello";
NSMutableArray * arr = [NSMutableArray arrayWithCapacity:0];
    // 遍历字符串,按字符来遍历。每个字符将通过block参数中的substring传出
    [str enumerateSubstringsInRange:NSMakeRange(0, str.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        [arr addObject:substring];     
    }];
NSLog(@"arr = %@", arr);

关于NSStringEnumerationOptions选项

typedef NS_OPTIONS(NSUInteger, NSStringEnumerationOptions) {
    // Pass in one of the "By" options:
    NSStringEnumerationByLines = 0,                       // Equivalent to lineRangeForRange:
    NSStringEnumerationByParagraphs = 1,                  // Equivalent to paragraphRangeForRange:
    NSStringEnumerationByComposedCharacterSequences = 2,  // 字符Equivalent to rangeOfComposedCharacterSequencesForRange:
    NSStringEnumerationByWords = 3,//词
    NSStringEnumerationBySentences = 4,//句子
    // ...and combine any of the desired additional options:
    NSStringEnumerationReverse = 1UL << 8,
    NSStringEnumerationSubstringNotRequired = 1UL << 9,
    NSStringEnumerationLocalized = 1UL << 10              // User's default locale
};
上一篇下一篇

猜你喜欢

热点阅读