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;
}
}