- #import <foundation/foundation.h>
- int main() {
- NSString *string = @"3k1f0a63712h9s45fo78";
-
- // 方法1
- // 用@""空字符替换@"[0-9]"(正则表达式 表示0-9数字) options:参数是使用正则表达式 range:参数是整个字符串范围
- NSString *newString = [string stringByReplacingOccurrencesOfString:@"[0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length)];
- NSLog(@"%@", newString); // 输出:kfahsfo
-
- // 方法2
- // 用@"0123456789"字符串里的字符创建一个字符集
- NSCharacterSet *numberSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
- // 用字符集里的字符分割字符串为一个个子串 返回一个存着子串的数组
- NSArray *array = [string componentsSeparatedByCharactersInSet:numberSet];
- // NSLog(@"%@", array); ("",k,f,a,"","","","",h,s,"",fo,"","") 数组里装着这些东西
- // 把数组元素用@""空字符连接成字符串
- NSString *str = [array componentsJoinedByString:@""];
- NSLog(@"%@", str); // 输出:kfahsfo
-
- // 方法3
- NSMutableString *newStr = [NSMutableString string];
- for (int i = 0; i < string.length; i++) {
- unichar c = [string characterAtIndex:i];
- if ( !(c >= '0' && c <= '9') ) {
- [newStr appendFormat:@"%c", c];
- }
- }
- NSLog(@"%@", newStr); // 输出:kfahsfo
-
- return 0;
- }
复制代码 |