NSCharacterSet使用
(一)NSCharacterSet作用:
对字符串进行上做过滤、删除或者分割操作
+ (NSCharacterSet *)controlCharacterSet; //控制符 + (NSCharacterSet *)whitespaceCharacterSet; //空格 + (NSCharacterSet *)whitespaceAndNewlineCharacterSet; //空格和换行 + (NSCharacterSet *)decimalDigitCharacterSet; //小数 + (NSCharacterSet *)letterCharacterSet; //文字 + (NSCharacterSet *)lowercaseLetterCharacterSet; //字母数字 + (NSCharacterSet *)uppercaseLetterCharacterSet; //可分解 + (NSCharacterSet *)nonBaseCharacterSet; + (NSCharacterSet *)alphanumericCharacterSet; //字母数字 + (NSCharacterSet *)decomposableCharacterSet; + (NSCharacterSet *)illegalCharacterSet; //非法 + (NSCharacterSet *)punctuationCharacterSet; //标点符号 + (NSCharacterSet *)capitalizedLetterCharacterSet; //大写 + (NSCharacterSet *)symbolCharacterSet; //符号 + (NSCharacterSet *)newlineCharacterSet NS_AVAILABLE(10_5, 2_0); //换行符
(二)NSCharacterSet简单使用:(只会操作字符串的首尾)
NSString *testString = @" .^this is just a test @"; /*去除字符串中的空格和换行*/ testString = [testString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; /*去除字符串中的标点*/ testString = [testString stringByTrimmingCharactersInSet:[NSCharacterSet punctuationCharacterSet]]; /*去除字符串中的符号*/ testString = [testString stringByTrimmingCharactersInSet:[NSCharacterSet symbolCharacterSet]]; NSLog(@"%@",testString);
结果输出:
* 如果想去除中间的,则把字符串分开进行操作:
NSString *string = @" Lorem * ipsum% dolar@ +sit ^amet. "; //去除首位空格 string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; //以空格为分割符分成单词数组 NSArray *components = [string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; NSMutableArray *newArr = [NSMutableArray array]; for (__strong NSString *subString in components) { //遍历数组,对每个单词进行处理 subString = [subString stringByTrimmingCharactersInSet:[NSCharacterSet symbolCharacterSet]]; subString = [subString stringByTrimmingCharactersInSet:[NSCharacterSet punctuationCharacterSet]]; [newArr addObject:subString]; } //重新以空格拼接还原字符串 string = [newArr componentsJoinedByString:@" "]; NSLog(@"%@",string);
结果输出:
Lorem ipsum dolar sit amet