NSString+YOHO.m 13.3 KB
//
//  NSString+YOHO.m
//  YH_Mall
//
//  Created by 张同海 on 15/5/28.
//  Copyright (c) 2015年 YOHO. All rights reserved.
//

#import "NSString+YOHO.h"
#import <CommonCrypto/CommonDigest.h>
#import "JTSHardwareInfo.h"
#import "OpenUDID.h"
#import <AdSupport/AdSupport.h>

@implementation NSString (YOHO)

- (NSString *)yh_md5String
{
    const char *cStr = [self UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

- (CGFloat)yh_priceValue
{
    return [[self stringByReplacingOccurrencesOfString:@"," withString:@""] floatValue];
}


- (BOOL)yh_isEmptyAfterTrimmingWhitespaceAndNewlineCharacters
{
    return [[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0;
}


- (NSString *)yh_stringByTrimmingWhitespaceAndNewlineCharacters
{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}


- (NSString *)URLEncodedStringWithCFStringEncoding:(CFStringEncoding)encoding
{
    return  CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)self, NULL, CFSTR("=,!$&'()*+;@?\n\"<>#\t :/"), encoding));
}


- (NSString *)yh_URLEncodedString
{
    return [self URLEncodedStringWithCFStringEncoding:kCFStringEncodingUTF8];
}



+ (NSString *)stringWithDate:(NSDate *)date dateFormat:(NSString *)format
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSString *dateFormat = nil;
    if (format == nil) {
        dateFormat = @"y.MM.dd HH: mm: ss";
    } else {
        dateFormat = format;
    }
    formatter.dateFormat = dateFormat;
    NSString *dateString = [formatter stringFromDate:date];
    return dateString;
}




// 长度是否在一个范围之内
- (BOOL)yh_isLenghGreaterThanOrEqual:(NSInteger)minimum lessThanOrEqual:(NSInteger)maximum
{
    return ([self length] >= minimum) && ([self length] <= maximum);
}


- (NSRange)yh_firstRangeOfURLSubstringi
{
    static NSDataDetector *dataDetector = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dataDetector = [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypeLink | NSTextCheckingTypeLink)
                                                       error:nil];
    });
    
    NSRange range = [dataDetector rangeOfFirstMatchInString:self
                                                    options:0
                                                      range:NSMakeRange(0, [self length])];
    return range;
}


- (NSString *)yh_firstURLSubstring
{
    NSRange range = [self yh_firstRangeOfURLSubstringi];
    if (range.location == NSNotFound) {
        return nil;
    }
    
    return [self substringWithRange:range];
}


- (NSArray *)yh_URLSubstrings
{
    static NSDataDetector *dataDetector = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dataDetector = [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypeLink | NSTextCheckingTypeLink)
                                                       error:nil];
    });
    
    NSArray *matches = [dataDetector matchesInString:self
                                             options:0
                                               range:NSMakeRange(0, [self length])];
    NSMutableArray *substrings = [NSMutableArray arrayWithCapacity:[matches count]];
    for (NSTextCheckingResult *result in matches) {
        [substrings addObject:[result.URL absoluteString]];
    }
    return [NSArray arrayWithArray:substrings];
}


- (NSString *)yh_firstMatchUsingRegularExpression:(NSRegularExpression *)regularExpression
{
    NSRange range = [regularExpression rangeOfFirstMatchInString:self
                                                         options:0
                                                           range:NSMakeRange(0, [self length])];
    if (range.location == NSNotFound) {
        return nil;
    }
    
    return [self substringWithRange:range];
}


- (NSString *)yh_firstMatchUsingRegularExpressionPattern:(NSString *)regularExpressionPattern
{
    NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:regularExpressionPattern
                                                                                       options:NSRegularExpressionCaseInsensitive
                                                                                         error:nil];
    return [self yh_firstMatchUsingRegularExpression:regularExpression];
}


- (BOOL)yh_matchesRegularExpressionPattern:(NSString *)regularExpressionPattern
{
    NSRange fullRange = NSMakeRange(0, [self length]);
    NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:regularExpressionPattern
                                                                                       options:NSRegularExpressionCaseInsensitive
                                                                                         error:nil];
    NSRange range = [regularExpression rangeOfFirstMatchInString:self
                                                         options:0
                                                           range:fullRange];
    if (NSEqualRanges(fullRange, range)) {
        return YES;
    }
    return NO;
}


- (NSRange)yh_rangeOfFirstMatchUsingRegularExpressionPattern:(NSString *)regularExpressionPattern
{
    NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:regularExpressionPattern
                                                                                       options:NSRegularExpressionCaseInsensitive
                                                                                         error:nil];
    NSRange range = [regularExpression rangeOfFirstMatchInString:self
                                                         options:0
                                                           range:NSMakeRange(0, [self length])];
    return range;
}


- (NSString *)yh_stringByReplacingMatchesUsingRegularExpressionPattern:(NSString *)regularExpressionPattern withTemplate:(NSString *)templ
{
    NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:regularExpressionPattern
                                                                                       options:NSRegularExpressionCaseInsensitive
                                                                                         error:nil];
    NSString *string = [regularExpression stringByReplacingMatchesInString:self
                                                                   options:0
                                                                     range:NSMakeRange(0, [self length])
                                                              withTemplate:templ];
    return string;
}


- (NSDictionary *)yh_URLParameters
{
    NSString *urlString = [self stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSRange rangeOfQuestionMark = [urlString rangeOfString:@"?" options:NSBackwardsSearch];
    if (rangeOfQuestionMark.location == NSNotFound) {
        return nil;
    }
    
    NSString *parametersString = [urlString substringFromIndex:(rangeOfQuestionMark.location + 1)];
    NSArray *pairs = [parametersString componentsSeparatedByString:@"&"];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:[pairs count]];
    for (NSString *aPair in pairs) {
        NSArray *keyAndValue = [aPair componentsSeparatedByString:@"="];
        if ([keyAndValue count] == 2) {
            [parameters setObject:keyAndValue[1] forKey:keyAndValue[0]];
        }
    }
    return parameters;
}

- (BOOL)yh_isPureDigital
{
    NSScanner* scan = [NSScanner scannerWithString:self];
    long long val;
    return [scan scanLongLong:&val] && [scan isAtEnd];
}

- (NSString *)yh_splitUrlWithWidth:(NSString *)width height:(NSString *)height mode:(NSString *)mode
{
    return [[[[self stringByReplacingOccurrencesOfString:@"{width}" withString:[NSString stringWithFormat:@"%zd",width.integerValue]] stringByReplacingOccurrencesOfString:@"{height}" withString:[NSString stringWithFormat:@"%zd",height.integerValue]] stringByReplacingOccurrencesOfString:@"{mode}" withString:mode] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

- (NSString *)yh_splitUrlWithWidth:(NSString *)width height:(NSString *)height
{
    return [self yh_splitUrlWithWidth:width height:height mode:@"2"];
}

- (NSMutableAttributedString *)yh_attributedStringWithLineSpacing:(CGFloat)lineSpacing lineBreakMode:(NSLineBreakMode)breakMode textAlignment:(NSTextAlignment)alignment
{
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:self];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpacing];
    [paragraphStyle setLineBreakMode:breakMode];
    [paragraphStyle setAlignment:alignment];
    
    [attributedStr addAttribute:NSParagraphStyleAttributeName
                          value:paragraphStyle
                          range:NSMakeRange(0, [self length])];
    return attributedStr;
}

-(NSMutableAttributedString *)yh_attributedStringFromStingWithFont:(UIFont *)font withLineSpacing:(CGFloat)lineSpacing withLineBreakMode:(NSLineBreakMode)breakMode
{
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:self attributes:@{NSFontAttributeName:font}];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpacing];
    [paragraphStyle setLineBreakMode:breakMode];
    
    [attributedStr addAttribute:NSParagraphStyleAttributeName
                          value:paragraphStyle
                          range:NSMakeRange(0, [self length])];
    return attributedStr;
}

-(NSMutableAttributedString *)yh_attributedStringFromStingWithFont:(UIFont *)font lineSpacing:(CGFloat)lineSpacing lineBreakMode:(NSLineBreakMode)breakMode alignment:(NSTextAlignment)alignment
{
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:self attributes:@{NSFontAttributeName:font}];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpacing];
    [paragraphStyle setLineBreakMode:breakMode];
    [paragraphStyle setAlignment:alignment];
    
    [attributedStr addAttribute:NSParagraphStyleAttributeName
                          value:paragraphStyle
                          range:NSMakeRange(0, [self length])];
    return attributedStr;
}

-(CGSize)yh_boundingRectWithSize:(CGSize)size withTextFont:(UIFont *)font withLineSpacing:(CGFloat)lineSpacing withLineBreakMode:(NSLineBreakMode)breakMode
{
    NSMutableAttributedString *attributedText = [self yh_attributedStringFromStingWithFont:font
                                                                        withLineSpacing:lineSpacing withLineBreakMode:breakMode];
    CGSize textSize = CGSizeZero;
    if (attributedText.length > 0) {
        textSize = [attributedText boundingRectWithSize:size
                                                       options:NSStringDrawingUsesLineFragmentOrigin
                                                       context:nil].size;
    }
    return textSize;
}

- (CGFloat)yh_heightWithFont:(UIFont *)font constrainedToWidth:(CGFloat)width
{
    return ceilf([self boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil].size.height);
}

- (NSString *)yh_floatString
{
    if ([self isKindOfClass:[NSString class]]) {
        CGFloat tmp = [self floatValue];
        NSString *str = [NSString stringWithFormat:@"%0.2f",tmp];
        return str;
    } else {
        return @"";
    }
}

- (NSString *)yh_anonymousName
{
    if(self.length == 0) {
        return self;
    }

    NSString *username = self;
    if ([username length] == 1||[username length] == 2) {
        NSRange range = NSMakeRange([username length]-1, 1);
        username = [username stringByReplacingCharactersInRange:range withString:@"*"];
        return username;
    } else {
        NSRange range = NSMakeRange(1, username.length-2);
        username = [username stringByReplacingCharactersInRange:range withString:@"***"];
    }
    return username;
}

- (NSString *)yh_stringByRemoveRMBSymbol
{
    return [[self stringByReplacingOccurrencesOfString:@"¥" withString:@""] stringByReplacingOccurrencesOfString:@"¥" withString:@""];

}

- (NSString *)yh_anonymousMoblie
{
    if(self.length == 0) {
        return self;
    }
    NSString *anonymousStr = self;
    for (int i = 0; i < anonymousStr.length; i ++) {
        if (anonymousStr.length < 3) {
            break;
        }else{
            if (i >=3 && i < 7) {
                NSRange range = NSMakeRange(i, 1);
                anonymousStr = [anonymousStr stringByReplacingCharactersInRange:range withString:@"*"];
            }
        }
    }
    return anonymousStr;
}

@end