iOS随笔小记-- 字符串去掉特殊字符(只保留大小写字母和数字)

2018-05-22  本文已影响40人  七一小月

直接调用removeSpecialCharacters方法就可以了

- (NSString *)removeSpecialCharacters:(NSString *)value{
    NSMutableString *string = [NSMutableString stringWithString:value];
    unichar c;
    for(int i=0;i<string.length;i++){
        c = [string characterAtIndex:i];
        if(![self charIsNum:c]){
            //First determine if it is a number. If it is not a number, continue to determine whether it is a letter.
            if(![self charIsZimu:c]){
                //If it is not a letter, it means neither a number nor a letter
                NSString *str = [NSString stringWithCharacters:&c length:1];
                NSLog(@" removeSpecialCharacters str=%@",str);
                NSRange range = NSMakeRange(i, 1);
                [string deleteCharactersInRange:range];
                --i;
            }
        }
    }

    NSString *newstr = [NSString stringWithString:string];
    NSLog(@" removeSpecialCharacters after str=%@",newstr);
    return newstr;
}

//Judging whether it is a number
-(BOOL)charIsNum:(unichar)chars{
    if(isdigit(chars)){
        return YES;
    }
    else {
        return NO;
    }
}

//Determine if it is a letter
-(BOOL)charIsZimu:(unichar)chars{
      if((chars<'A'||chars>'Z')&&(chars<'a'||chars>'z'))
      {
            return  NO;
      }
      else {
            return YES;
      }
}
上一篇下一篇

猜你喜欢

热点阅读