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

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

作者: 七一小月 | 来源:发表于2018-05-22 11:23 被阅读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;
          }
    }
    

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/zwrhjftx.html