NSString常用的类别


#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>

@interface NSString (Extension)

//根据字体返回宽高
- (CGSize)textSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode;

//是否是子串
- (BOOL)isContainSubString:(NSString *)subString;

//是否是表情
- (BOOL)stringContainsEmoji;

//是否是手机号
- (BOOL)isMobileNumber;

//是否是电话号码
//- (BOOL)isFixPhoneNumber;

//是否是邮箱
- (BOOL)isAvailableEmail;

//是否是纯数字
- (BOOL)isNumText;
/**
 是否是身份证
 */
- (BOOL)isIdentityNumber;

//最多显示两位小数
+(NSString *)returnActualFormatNumber:(double)number;

//保留几位小数
+(NSString *)returnDetailFormatNumber:(double)number leaveCount:(NSInteger)count;

//设置富文本
+ (NSMutableAttributedString *)setNbLabelTextProperty:(NSString *)text
                                               string:(NSString *)string
                                            textColor:(UIColor *)color
                                             textFont:(UIFont *)font;

+ (NSMutableAttributedString *)attributeStringWithText:(NSString *)text
                                         withLineSpace:(CGFloat )lineSpace
                                     withLineBreakMode:(NSLineBreakMode )lineBreakMode
                                              withFont:(UIFont *)font;

+ (NSMutableAttributedString *)attributebLabelText:(NSString *)text
                                        withTextColor:(UIColor *)textColor
                                        withLineSpace:(CGFloat)lineSpace
                                         withTextFont:(UIFont *)textFont
                                 withExtraStringArray:(NSArray *)extraStringArr
                                  withExtraColorArray:(NSArray *)extraColorArr
                                   withExtraFontArray:(NSArray *)extraFont;
/**
 是否是身份证
 */
+ (BOOL)validateIdentityCard:(NSString *)identityCard;

//是否有空格
- (BOOL)isHaveSpaceInString;

//是否有中文字符
- (BOOL)isHaveChineseInString;

//是否是url
- (BOOL)isWebUrlStr;
@end

#import "NSString+Extension.h"

@implementation NSString (Extension)

- (CGSize)textSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode
{
    CGSize textSize;
    if ([Device isIOS7orLater]) {
        
        if (CGSizeEqualToSize(size, CGSizeZero)) {
            
            textSize =  [self sizeWithAttributes:@{NSFontAttributeName:font}];
        }
        else{
            
            NSStringDrawingOptions option = NSStringDrawingUsesLineFragmentOrigin;
            //NSStringDrawingTruncatesLastVisibleLine如果文本内容超出指定的矩形限制,文本将被截去并在最后一个字符后加上省略号。 如果指定了NSStringDrawingUsesLineFragmentOrigin选项,则该选项被忽略 NSStringDrawingUsesFontLeading计算行高时使用行间距。(译者注:字体大小+行间距=行高)
            NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
            CGRect rect = [self boundingRectWithSize:size
                                             options:option
                                          attributes:attributes
                                             context:nil];
            textSize = rect.size;
        }
        
    }
    else{
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
        
        if (CGSizeEqualToSize(size, CGSizeZero)) {
            
            textSize =[self sizeWithFont:font];
        }
        else{
            
            textSize =[self  sizeWithFont:font constrainedToSize:size lineBreakMode:lineBreakMode];
        }
#endif
    }
    return textSize;
}

- (BOOL)isContainSubString:(NSString *)subString{
    
    if([self rangeOfString:subString].location != NSNotFound)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

- (BOOL)stringContainsEmoji
{
    __block BOOL returnValue = NO;
    
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    if ([@"➋➌➍➎➏➐➑➒" isContainSubString:self]) {
        
        returnValue = NO;
    }
    return returnValue;
}

//- (BOOL)isMobileNumber
//{
//    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
//    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
//    return [phoneTest evaluateWithObject:self];
//}

- (BOOL)isMobileNumber
{
    if (self.length != 11)
    {
        return NO;
    }
    return YES;
    
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     * 联通号段: 130,131,132,155,156,185,186,145,176,1709
     * 电信号段: 133,153,180,181,189,177,1700
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$";
    /**
     * 中国移动:China Mobile
     * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     */
    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
    /**
     * 中国联通:China Unicom
     * 130,131,132,155,156,185,186,145,176,1709
     */
    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    /**
     * 中国电信:China Telecom
     * 133,153,180,181,189,177,1700
     */
    NSString *CT = @"(^1(33|53|77|73||8[019])\\d{8}$)|(^1700\\d{7}$)";
    
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:self] == YES)
        || ([regextestcm evaluateWithObject:self] == YES)
        || ([regextestct evaluateWithObject:self] == YES)
        || ([regextestcu evaluateWithObject:self] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
- (BOOL)isWebUrlStr{
    
  
    if (self.length == 0)
    {
        return NO;
    }
    NSString * urlStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@;#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@;#$%^&*+?:_/=<>]*)?)";
    
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlStr];
    
    if ([regextestmobile evaluateWithObject:self] == YES)
    {
        return YES;
    }
    else
    {
        return NO;
    }
   
}

- (BOOL)isAvailableEmail
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

- (BOOL)isIdentityNumber{
    NSString *phoneRegex = @"^(\\d{15}$|^\\d{18}$|^\\d{17}(\\d|X|x))$";
    NSPredicate *identityTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [identityTest evaluateWithObject:self];
}


- (BOOL)isNumText{
    
    //判断是不是纯数字
    [NSCharacterSet decimalDigitCharacterSet];
    if ([[self stringByTrimmingCharactersInSet: [NSCharacterSet decimalDigitCharacterSet]] stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]].length >0) {
        return NO;
    }else{
        return YES;
    }

}


+(NSString *)returnActualFormatNumber:(double)number
{
//    NSString *thirdNum = [NSString stringWithFormat:@"%0.3f",number];
//    number = [thirdNum doubleValue];
    
    //最多保留两位小数
    number = round(number*100)/100;
    
    NSArray *numArray =[[NSString stringWithFormat:@"%.2f",number] componentsSeparatedByString:@"."];
    
    NSString *firstNum =[numArray firstObject];
    NSString *secondNum =[numArray lastObject];
    
    if ([secondNum doubleValue] == 0) {
        
        return firstNum;
    }
    else
    {
        if ([[secondNum substringFromIndex:1] doubleValue] != 0) {
            
            return [NSString stringWithFormat:@"%.2f",number];
        }
        else{
            
            return [NSString stringWithFormat:@"%.1f",number];
        }
    }
    return nil;
}

+(NSString *)returnDetailFormatNumber:(double)number leaveCount:(NSInteger)count{

    number = round(number*100)/100;
    
    NSArray *numArray =[[NSString stringWithFormat:@"%@",@(number)] componentsSeparatedByString:@"."];
    
    NSString *firstNum =[numArray firstObject];
    NSString *secondNum =[numArray lastObject];
    
    if ([secondNum doubleValue] == 0) {
        
        return firstNum;
    }
    else{
    
        NSString *subSecondStr = [secondNum substringToIndex:count];
        
        return [NSString stringWithFormat:@"%@.%@",firstNum,subSecondStr];
    }
    return nil;
}


+ (NSMutableAttributedString *)setNbLabelTextProperty:(NSString *)text
                                               string:(NSString *)string
                                            textColor:(UIColor *)color
                                             textFont:(UIFont *)font
{
    NSRange range;
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:text];
    
    if (string != nil && ![string isEqualToString:@""]) {
        range = [text rangeOfString:string];
    }else{
        range = NSMakeRange(0, 0);
    }
    
    [str addAttribute:NSForegroundColorAttributeName value:color range:range];
    [str addAttribute:NSFontAttributeName value:font range:range];
    
    return str;
}

+ (NSMutableAttributedString *)attributeStringWithText:(NSString *)text withLineSpace:(CGFloat )lineSpace withLineBreakMode:(NSLineBreakMode )lineBreakMode withFont:(UIFont *)font
{
    NSMutableParagraphStyle *paragraphStyle =[[NSMutableParagraphStyle  alloc]init];
    paragraphStyle.lineSpacing = lineSpace;
    paragraphStyle.lineBreakMode = lineBreakMode;
    
    NSMutableAttributedString *attributeStr =[[NSMutableAttributedString alloc]initWithString:text
                                                                                   attributes:@{NSFontAttributeName:font,NSParagraphStyleAttributeName:paragraphStyle}];
    return attributeStr;
}

+ (NSMutableAttributedString *)attributebLabelText:(NSString *)text
                                        withTextColor:(UIColor *)textColor
                                        withLineSpace:(CGFloat)lineSpace
                                         withTextFont:(UIFont *)textFont
                                 withExtraStringArray:(NSArray *)extraStringArr
                                  withExtraColorArray:(NSArray *)extraColorArr
                                   withExtraFontArray:(NSArray *)extraFont;
{
    if (!IsStrEmpty(text)) {
        
        NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:text];
        [attributeStr addAttribute:NSForegroundColorAttributeName value:textColor range:NSMakeRange(0, text.length)];
        [attributeStr addAttribute:NSFontAttributeName value:textFont range:NSMakeRange(0, text.length)];
        
        NSMutableParagraphStyle * paragraphStyle =[[NSMutableParagraphStyle alloc]init];
        [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
        [paragraphStyle setLineSpacing:lineSpace];
        [attributeStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, text.length)];
        
        for (int i=0; i< extraStringArr.count; i++) {
            
            NSString * str = extraStringArr[i];
            NSRange range = [text rangeOfString:str];
            [attributeStr addAttribute:NSForegroundColorAttributeName value:extraColorArr[i] range:range];
            [attributeStr addAttribute:NSFontAttributeName value:extraFont[i] range:range];
        }
        return attributeStr;
    }
    
    return nil;
}

+ (BOOL)validateIdentityCard:(NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}

- (BOOL)isHaveSpaceInString
{
    NSRange _range = [self rangeOfString:@" "];
    if (_range.location != NSNotFound) {
        return YES;
    }else {
        return NO;
    }
}

- (BOOL)isHaveChineseInString
{
    for(NSInteger i = 0; i < [self length]; i++){
        
        int a = [self characterAtIndex:i];
        if (a > 0x4e00 && a < 0x9fff) {
            return YES;
        }
    }
    return NO;
}

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,590评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,808评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,151评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,779评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,773评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,656评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,022评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,678评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,038评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,756评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,411评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,005评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,973评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,053评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,495评论 2 343

推荐阅读更多精彩内容