字符串的操作NSCharacterSet

2016-05-09  本文已影响172人  三岁就很乖

//有字符串“      O~I^C_U>A      ",拆分出单个字母:
    NSString *str =@"      O~I^C_U>A       ";
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];//去掉前边和后边的空格
    NSCharacterSet * charSet = [NSCharacterSet characterSetWithCharactersInString:@"^~_>"];
    NSArray *arr = [str componentsSeparatedByCharactersInSet:charSet];
    //输出看效果
    [arr enumerateObjectsUsingBlock:^(id obj,NSUInteger idx,BOOL *stop) {
        NSLog(@"O~I^C_U>A->[%@]", obj);
    }];
    
    
    
    //关于invertedSet
    NSString *string =@"   ff3,45_69 . %><a     ";
    NSString * kNumber =@"0123456789.";
    NSCharacterSet *numberSet = [[NSCharacterSet characterSetWithCharactersInString:kNumber]invertedSet];
    //invertedSet方法是去反字符,把所有的除了kNumber里的字符都找出来(包含去空格功能)
    NSString *fieldString = [[string componentsSeparatedByCharactersInSet:numberSet]componentsJoinedByString:@""];
    NSLog(@"number__[%@]", fieldString);

输出结果:

O~I^C_U>A->[O]
O~I^C_U>A->[I]
O~I^C_U>A->[C]
O~I^C_U>A->[U]
O~I^C_U>A->[A]
number__[34569.]

上一篇下一篇

猜你喜欢

热点阅读