NSCharacterSet-字符集使用总结

本文详细介绍了NSCharacterSet及其可变类型NSMutableCharacterSet的功能与用法,包括如何使用它们进行字符过滤、删除和分割等操作,并通过多个实例展示了如何与NSString配合使用。

简介

NSCharacterSet ,以及它的可变类型 NSMutableCharacterSet,用面向对象的方式来表示一组Unicode字符。它经常与NSString及NSScanner组合起来使用,在不同的字符上做过滤、删除或者分割操作。

方法和属性介绍

NSCharacterSet 中提供的下面属性都是只读的, 且在NSMutableCharacterSet中有一致的类方法

1.controlCharacterSet //控制符的字符集
2.whitespaceCharacterSet //空格的字符集
3.whitespaceAndNewlineCharacterSet //空格和换行符的字符集
4.decimalDigitCharacterSet //十进制数字的字符集
5.letterCharacterSet //字母的字符集
6.lowercaseLetterCharacterSet //小写字母的字符集
7.uppercaseLetterCharacterSet //大写字母的字符集
8.nonBaseCharacterSet //非基础的字符集
9.alphanumericCharacterSet //字母和数字的字符集
10.decomposableCharacterSet //可分解
11.illegalCharacterSet //非法的字符集
12.punctuationCharacterSet //标点的字符集
13.capitalizedLetterCharacterSet //首字母大写的字符集
14.symbolCharacterSet //符号的字符集
15.newlineCharacterSet //换行符的字符集

NSCharacterSet 和 NSMutableCharacterSet一致的类方法

//返回一个指定范围的字符集,取自小写字母字符集
+ (NSCharacterSet *)characterSetWithRange:(NSRange)aRange;
//返回一个包含当前字符串的字符集
+ (NSCharacterSet *)characterSetWithCharactersInString:(NSString *)aString;
//返回包含由给定位图表示形式确定的字符的字符集,此方法对于使用来自文件或其他外部数据源的数据创建字符集
+ (NSCharacterSet *)characterSetWithBitmapRepresentation:(NSData *)data;
//返回从位图表示中读取的字符集,存储在文件中给定的路径。
+ (nullable NSCharacterSet *)characterSetWithContentsOfFile:(NSString *)fName;

NSCharacterSet中的其它方法或属性

//指定字符集是包含于在于当前字符集
- (BOOL)characterIsMember:(unichar)aCharacter;
//以二进制格式编码接收器的NSData对象,此格式适用于保存到文件或以其他方式传输或归档
@property (readonly, copy) NSData *bitmapRepresentation;
//反转字符集,仅包含当前字符集中不存在的字符
@property (readonly, copy) NSCharacterSet *invertedSet;

NSMutableCharacterSet中其它方法

- (void)addCharactersInRange:(NSRange)aRange;
- (void)removeCharactersInRange:(NSRange)aRange;
- (void)addCharactersInString:(NSString *)aString;
- (void)removeCharactersInString:(NSString *)aString;
- (void)formUnionWithCharacterSet:(NSCharacterSet *)otherSet;
- (void)formIntersectionWithCharacterSet:(NSCharacterSet *)otherSet;
- (void)invert;

延伸

常与NSString 的一些方法结合使用, 来达到某些效果

//返回一个指定字符集分隔开的子字符串数组
- (NSArray<NSString *> *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator NS_AVAILABLE(10_5, 2_0);
//返回一个去除两端指定字符集的字符串
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set;
//返回指定字符集在当前字符串中的第一个符合条件的范围
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet;

NSArray的一些方法:

//在数组中子串之间插入指定字符
- (NSString *)componentsJoinedByString:(NSString *)separator;

应用

    NSString *testString = @"This is the test string for %a*b*c&";
    NSArray *divArr = [testString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"abc"]];
    NSLog(@"%@",divArr);

打印结果:

(
    "This is the test string for %",
    "*",
    "*",
    "&"
)

举例使用

##1.去掉首尾空格

NSString *testString = @"      This is the string contains whitespace in beginning and ending     ";
    NSString *whitesspaceStr = [testString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSLog(@"%@",whitesspaceStr);

打印结果: This is the string contains whitespace in beginning and ending

##2.去除首尾指定字符串

    NSString *str=@"哈哈呵呵嘿嘿吼吼";
    NSCharacterSet *cs= [NSCharacterSet characterSetWithCharactersInString:@"哈吼"];
    NSString *strResult = [str stringByTrimmingCharactersInSet:cs];
    NSLog(@"%@",strResult);

打印结果: 呵呵嘿嘿

##3.用指定字符串替代当前字符中的指定字符集中的字符串

    NSMutableCharacterSet *letter = [NSMutableCharacterSet lowercaseLetterCharacterSet];
    NSCharacterSet *decimalDigit = [NSCharacterSet decimalDigitCharacterSet];
    [letter formUnionWithCharacterSet:decimalDigit];
    NSString *string = @"g8!hgr3@09#23uiq%^78sjn453t78&13gesg*wt53(545y45)q3at";
    NSLog(@"%@",[[string componentsSeparatedByCharactersInSet:letter] componentsJoinedByString:@"_"]);
    [letter invert];  //字母数字反转
    NSLog(@"%@",[[string componentsSeparatedByCharactersInSet:letter] componentsJoinedByString:@"_"]);

打印结果:

__!____@__#_____%^___________&______*____(______)____
g8_hgr3_09_23uiq__78sjn453t78_13gesg_wt53_545y45_q3at

##4.去除所有空格

    NSString *string = @"  a b  cd   ef gh ij    klm   nopq rstu v  w x   y z  ";
    NSLog(@"%@",[[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""]);

打印结果: abcdefghijklmnopqrstuvwxyz

##5.与NSPredicate结合使用压缩空格

    NSString *string = @"  Additional    setup   after    loading the     view.";
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    NSArray *components = [string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    components = [components filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self <> ''"]];
    
    string = [components componentsJoinedByString:@" "];
    NSLog(@"%@", string);

打印结果: Additional setup after loading the view.

##6.判断字符串是否只包含数字

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

##7.在UITextFieldDelegate方法中, 限制只能输入数字和小数点, 且第一位不可以输入小数点, 小数点只能输入一个

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSCharacterSet *cs;
    NSUInteger nDotLoc = [textField.text rangeOfString:@"."].location;
    if (NSNotFound == nDotLoc && 0 != range.location) {
        cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
    }else{
        cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
    }
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL basicTest = [string isEqualToString:filtered];
    
    if (!basicTest) {
        return NO;
    }
    return YES;
}

资料推荐:
NSCharacter​Set

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值