NSCharacterSet 字符集的使用
2017-08-15 本文已影响141人
yuJiaMoMo
1.简介
NSCharacterSet ,以及它的可变类型 NSMutableCharacterSet,用面向对象的方式来表示一组Unicode字符。它经常与NSString及NSScanner组合起来使用,在不同的字符上做过滤、删除或者分割操作。
1.1 先来看下面的例子
需求: 有一个字符串:@"今天我们来学习NSCharacterSet我们快乐",去除字符串中所有的@"今"、@"我"、@"s"。 【注意】s是小写 思考:如果是你怎么解决? 自己写。 用 NSCharacterSet
1.1.1 自己写,如下:
NSString *str = @"今天我们来学习NSCharacterSet我们快乐";
NSString *str1 = @"我s今";
NSMutableString *resultStr = [[NSMutableString alloc]init];
for (int i = 0; i < str.length; i++) {
NSString *indexStr = [str substringWithRange:NSMakeRange(i, 1)];
if (![str1 containsString:indexStr]) {
[resultStr appendString:indexStr];
}
}
NSLog(@"自己写---%@",resultStr);
//输出结果 "自己写---天们来学习NSCharacterSet们快乐"
1.1.2 用 NSCharacterSet,如下:
NSString *str = @"今天我们来学习NSCharacterSet我们快乐";
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"我s今"];
NSArray *setArr = [str componentsSeparatedByCharactersInSet:characterSet];
NSString *resultStr1 = [setArr componentsJoinedByString:@""];
NSLog(@"拆分后的字符串数组------%@\n最终字符串------%@",setArr,resultStr1);
//输出结果 "自己写---天们来学习NSCharacterSet们快乐"
总结: 至此,通过上面的两个方法,已经解决了需求的问题。通过自己写,结合用NSCharacterSet,可以推断出NSCharacterSet类似一个字符串处理工具类,而事实上,由名字也可以看出,它确实是!
2.方法和属性介绍:
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;
举例使用
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;
}
8.限制手机号码正确输入
if (textField == self.userNameTextField) {//限时手机号输入
_previousTextFieldContent = textField.text;
_previousSelection = textField.selectedTextRange;
NSLog(@"--------- textField.text:%@,textField.selectedTextRange:%@,range:(%ld,%ld),string:%@",textField.text,textField.selectedTextRange,range.location,range.length,string);
if (range.location == 0){
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"1"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
BOOL basicTest = [string isEqualToString:filtered];
if (!basicTest){
// [self showMyMessage:@"只能输入数字"];
return NO;
}
}
else if (range.location == 1) {
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"^[3,4,5,7,8]$"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
BOOL basicTest = [string isEqualToString:filtered];
if (!basicTest){
//[self showMyMessage:@"只能输入数字"];
return NO;
}
}
if (range.location > 12) {
return NO;
}
}