// // FLStringHelper.m // FirstLink // // Created by unicode on 14-9-25. // Copyright (c) 2014年 FirstLink. All rights reserved. // #import // Need to import for CC_MD5 access #import "NSDate+Category.h" @implementation NSString (MyAdditions) - (NSString *)md5 { const char *cStr = [self UTF8String]; unsigned char result[32]; CC_MD5( cStr, (CC_LONG)strlen(cStr), result ); return [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%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], result[16], result[17],result[18], result[19], result[20], result[21],result[22], result[23], result[24], result[25],result[26], result[27], result[28], result[29],result[30], result[31]]; } @end #import "FLStringHelper.h" @implementation FLStringHelper + (NSString*)convertNumberToString:(int)num { return [NSString stringWithFormat:@"%d", num]; } + (CGRect)rectOfString:(NSString*)text font:(UIFont*)font width:(CGFloat)width { NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys: font, NSFontAttributeName, nil]; if (!text || text.length == 0) { return CGRectZero; } NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text attributes:attributesDictionary]; CGRect rect = [string boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) context:nil]; return rect; } + (CGRect)rectOfString:(NSString *)text font:(UIFont *)font height:(CGFloat)height { if (![FLStringHelper isValidString:text]) return CGRectZero; NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys: font, NSFontAttributeName, nil]; NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text attributes:attributesDictionary]; CGRect rect = [string boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) context:nil]; return rect; } + (CGSize)sizeOfAttributeString:(NSString *)text font:(UIFont *)font width:(CGFloat)width maxRow:(int)maxRow { if (![FLStringHelper isValidString:text]) return CGSizeZero; NSAttributedString *attributeString = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName : font}]; return [TTTAttributedLabel sizeThatFitsAttributedString:attributeString withConstraints:CGSizeMake(width, CGFLOAT_MAX) limitedToNumberOfLines:maxRow]; } + (NSString*)replaceNilWithEmpty:(NSString *)string { if (!string) { return @""; } return string; } + (NSString*)convertFenToYuan:(NSString *)fen { if (!fen || fen.length == 0) { return @""; } // TODO: 格式检查校验 NSNumber *yuan = [NSNumber numberWithDouble:fen.doubleValue/100]; return [NSString stringWithFormat:@"%.2lf",yuan.doubleValue]; } + (CGFloat)convertFenStringToYuanValue:(NSString *)fenStr{ if (!fenStr || ![fenStr isKindOfClass:[NSString class]] || fenStr.length == 0) { return 0.0f; } return fenStr.floatValue / 100.0f; } + (NSString *)convertFenToRMBmoneyString:(NSString*)fen{ return [NSString stringWithFormat:@"¥%@", [self convertFenToYuan:fen]]; } #pragma mark - Time Formate + (NSString*)componentOfDay:(NSString*)time { if (time == nil || time.length <= 0) { return nil; } return [time substringToIndex:10]; } + (NSDateFormatter *)dateFormat { static NSDateFormatter *dateFormat = nil; static dispatch_once_t once_token; dispatch_once(&once_token, ^{ dateFormat = [[NSDateFormatter alloc] init]; }); return dateFormat; } + (NSString*)convertStringToTipTime:(NSString *)time { return [self convertStringToTipTime:time formate:@"yyyy-MM-dd HH:mm:ss"]; } + (NSString *)convertStringToTipTime:(NSString *)time formate:(NSString *)formate{ if (!time) { return @"1分钟前"; } // 2014-10-12T12:12:12 NSDateFormatter *dateFormat = [FLStringHelper dateFormat]; [dateFormat setDateFormat:formate]; NSMutableString *mutString = [NSMutableString stringWithString:time]; NSString *temp = [mutString stringByReplacingOccurrencesOfString:@"T" withString:@" "]; NSDate *date = [dateFormat dateFromString:temp]; // TODO: relpace current with time from server NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitMinute | NSCalendarUnitHour | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date toDate:[NSDate date] options:0]; if (components.year > 0 || components.month > 0 || components.day > 0) { return [FLStringHelper componentOfDay:time]; } if (components.hour > 0) { return [NSString stringWithFormat:@"%ld小时前", (long)components.hour]; } if (components.minute > 0) { return [NSString stringWithFormat:@"%ld分钟前", (long)components.minute]; } return @"1 分钟前"; } + (NSDateComponents*)convertSecondToComponents:(NSTimeInterval)second { NSDate *startDate = [NSDate date]; NSDate *endDate = [NSDate dateWithTimeInterval:second sinceDate:startDate]; NSCalendarUnit unit = NSCalendarUnitSecond | NSCalendarUnitMinute | NSCalendarUnitHour | NSCalendarUnitDay; NSDateComponents *components = [[NSCalendar currentCalendar] components:unit fromDate:startDate toDate:endDate options:NSCalendarWrapComponents]; return components; } + (NSString*)dateForMessage:(NSDate *)date { if (!date) return nil; NSDateFormatter *dateFormat = [FLStringHelper dateFormat]; [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; return [dateFormat stringFromDate:date]; } + (NSString*)convertDate:(NSDate *)date formate:(NSString *)formate { if (!date) return nil; NSDateFormatter *dateFormat = [FLStringHelper dateFormat]; [dateFormat setDateFormat:formate]; return [dateFormat stringFromDate:date]; } + (NSDate *)convertToDateFromString:(NSString *)string { if (!string || string.length == 0) return nil; NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss"; NSString *dateString = [string stringByReplacingOccurrencesOfString:@"T" withString:@" "]; return [formatter dateFromString:dateString]; } + (NSDate *)convertToShortDateFromString:(NSString *)string{ if (!string || string.length == 0) return nil; NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; formatter.dateFormat = @"yyyy-MM-dd"; NSString *dateString = [string stringByReplacingOccurrencesOfString:@"T" withString:@" "]; return [formatter dateFromString:dateString]; } + (NSString *)convertDictionary2String:(NSDictionary *)dict { if (!dict) return nil; NSError *error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; if (!error) { return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; } return nil; } + (NSString*)nicknames:(NSArray*)array count:(int)count { NSMutableString *mutableString = [NSMutableString string]; for (int index = 0; index < array.count && index < count; index++) { [mutableString appendString:array[index]]; [mutableString appendString:@","]; } if (mutableString.length > 0) { return [mutableString substringToIndex:mutableString.length-1]; } return nil; } #pragma mark - CDN Paramater String + (NSString*)cdnParamaterString:(int)width { return [NSString stringWithFormat:@"@%dw_90Q_1l_%dx", width, (int)[UIScreen mainScreen].scale]; } + (NSString*)cdnParamaterString:(int)width height:(int)height { return [NSString stringWithFormat:@"@%dw_%dh_1e_1l_1c_%dx_1o", width, height, (int)[UIScreen mainScreen].scale]; } + (NSString *)convertToShortDateStringFromString:(NSString *)timeString { if (!timeString || timeString.length == 0) return nil; NSRange range = [timeString rangeOfString:@"T"]; NSString *shortString = [timeString substringToIndex:range.location]; return shortString; } + (NSString *)convertToPredigestStringFromString:(NSString *)timeString { return [self convertToPredigestStringFromString:timeString baseTime:nil]; } + (NSString *)convertToPredigestStringFromString:(NSString *)timeString baseTime:(NSDate *)baseTime{ if (!timeString || timeString.length == 0) return nil; NSDate *nowDate = [NSDate date]; if ([baseTime isKindOfClass:[NSDate class]]) { nowDate = baseTime; } NSString *shortDateString = [FLStringHelper convertToShortDateStringFromString:timeString]; NSDate *compareTime = [FLStringHelper convertToDateFromString:timeString]; NSTimeInterval countTimeSecond = [nowDate timeIntervalSinceDate:compareTime]; if (countTimeSecond <= 0) return nil; NSDateComponents *dateComponent = [FLStringHelper convertSecondToComponents:countTimeSecond]; if (dateComponent.day > 0) return shortDateString; if (dateComponent.hour > 0) return [NSString stringWithFormat:@"%ld小时前", (long)dateComponent.hour]; if (dateComponent.minute > 0) return [NSString stringWithFormat:@"%ld分钟前", (long)dateComponent.minute]; return [NSString stringWithFormat:@"1分钟前"]; } + (NSString *)convertToPredigestStringFromTimeInterval:(NSTimeInterval)timeInterval shortTimeStr:(NSString *)shortTimeStr{ if (timeInterval <= 0) return nil; NSDateComponents *dateComponent = [FLStringHelper convertSecondToComponents:timeInterval]; if (dateComponent.day > 0) return shortTimeStr; if (dateComponent.hour > 0) return [NSString stringWithFormat:@"%ld小时前", (long)dateComponent.hour]; if (dateComponent.minute > 0) return [NSString stringWithFormat:@"%ld分钟前", (long)dateComponent.minute]; return [NSString stringWithFormat:@"1分钟前"]; } + (NSString *)convertTimeIntervalToCountString:(NSTimeInterval)timeInterval { if (timeInterval <= 0) return @"0天0小时0分0秒"; NSDateComponents *dateComponet = [FLStringHelper convertSecondToComponents:timeInterval]; NSString *days = [NSString stringWithFormat:@"%ld", (long)dateComponet.day]; NSString *hours = [NSString stringWithFormat:@"%ld", (long)dateComponet.hour]; NSString *minuts = [NSString stringWithFormat:@"%ld", (long)dateComponet.minute]; NSString *seconds = [NSString stringWithFormat:@"%ld", (long)dateComponet.second]; NSString *normalString = [NSString stringWithFormat:@"%@天%@小时%@分%@秒", days, hours, minuts, seconds]; return normalString; } + (NSString *)convertTimeIntervalToHourCountString:(NSTimeInterval)timeInterval { if (timeInterval <= 0) return @"0小时0分0秒"; NSDateComponents *dateComponet = [FLStringHelper convertSecondToComponents:timeInterval]; NSString *hours = [NSString stringWithFormat:@"%ld", ((long)dateComponet.hour + dateComponet.day*24)]; NSString *minuts = [NSString stringWithFormat:@"%02ld", (long)dateComponet.minute]; NSString *seconds = [NSString stringWithFormat:@"%02ld", (long)dateComponet.second]; NSString *normalString = [NSString stringWithFormat:@"%@小时%@分%@秒", hours, minuts, seconds]; return normalString; } + (NSString *)convertTimeIntervalToHourCountStringStyleColon:(NSTimeInterval)timeInterval { if (timeInterval <= 0) return @"00:00:00"; NSDateComponents *dateComponet = [FLStringHelper convertSecondToComponents:timeInterval]; NSString *hours = [NSString stringWithFormat:@"%ld", ((long)dateComponet.hour + dateComponet.day*24)]; NSString *minuts = [NSString stringWithFormat:@"%02ld", (long)dateComponet.minute]; NSString *seconds = [NSString stringWithFormat:@"%02ld", (long)dateComponet.second]; NSString *normalString = [NSString stringWithFormat:@"%@:%@:%@", hours, minuts, seconds]; return normalString; } + (NSString *)convertToCommonFormateFromString:(NSString *)timeString baseTime:(NSString *)baseTime{ if (!timeString || timeString.length == 0) return nil; NSDate *nowDate = [NSDate date]; if ([FLStringHelper isValidString:baseTime]) { nowDate = [FLStringHelper convertToDateFromString:baseTime]; } NSDate *compareTime = [FLStringHelper convertToDateFromString:timeString]; NSTimeInterval countTimeSecond = [nowDate timeIntervalSinceDate:compareTime]; if (countTimeSecond <= 0) return nil; NSDateComponents *dateComponent = [self convertSecondToComponents:countTimeSecond baseTime:baseTime]; if (dateComponent.day > 0) return [self convertToTimeStrNoYear:timeString]; if (dateComponent.hour > 0) return [NSString stringWithFormat:@"%ld小时前", (long)dateComponent.hour]; if (dateComponent.minute > 3) return [NSString stringWithFormat:@"%ld分钟前", (long)dateComponent.minute]; return [NSString stringWithFormat:@"刚刚"]; } +(NSDateComponents *)convertToComponentsFormateFromString:(NSString *)timeString baseTime:(NSString *)baseTime{ if (!timeString || timeString.length == 0) return nil; NSDate *nowDate = [NSDate date]; if ([FLStringHelper isValidString:baseTime]) { nowDate = [FLStringHelper convertToDateFromString:baseTime]; } NSDate *compareTime = [FLStringHelper convertToDateFromString:timeString]; NSTimeInterval countTimeSecond = [compareTime timeIntervalSinceDate:nowDate]; if (countTimeSecond <= 0) return nil; NSDateComponents *dateComponent = [self convertSecondToComponents:countTimeSecond baseTime:baseTime]; return dateComponent; } + (NSString *)convertToTimeStrNoYear:(NSString *)timeStr{ NSDateFormatter *dateFormat = [FLStringHelper dateFormat]; [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSMutableString *mutString = [NSMutableString stringWithString:timeStr]; NSString *temp = [mutString stringByReplacingOccurrencesOfString:@"T" withString:@" "]; NSDate *date = [dateFormat dateFromString:temp]; if (!date) return nil; NSString *fullString = [dateFormat stringFromDate:date]; if (fullString.length >= 19){ NSString *dayStr = [fullString substringWithRange:NSMakeRange(5, 5)]; NSString *hourStr = [fullString substringWithRange:NSMakeRange(11, 5)]; fullString = [dayStr stringByAppendingString:@" "]; fullString = [fullString stringByAppendingString:hourStr]; } return fullString; } + (NSDateComponents*)convertSecondToComponents:(NSTimeInterval)second baseTime:(NSString *)baseTime{ NSDate *startDate = [FLStringHelper convertToDateFromString:baseTime]; NSDate *endDate = [NSDate dateWithTimeInterval:second sinceDate:startDate]; NSCalendarUnit unit = NSCalendarUnitSecond | NSCalendarUnitMinute | NSCalendarUnitHour | kCFCalendarUnitDay; NSDateComponents *components = [[NSCalendar currentCalendar] components:unit fromDate:startDate toDate:endDate options:NSCalendarWrapComponents]; return components; } + (NSTimeInterval)timeIntervalFromString:(NSString *)dateString { NSDate *date = [FLStringHelper convertToDateFromString:dateString]; return [date timeIntervalSince1970]; } + (BOOL)isUrlString:(NSString *)string { if (string.length < 5) return NO; NSString *headerString = [string substringToIndex:4]; if ([headerString isEqualToString:@"http"]) return YES; return NO; } + (NSAttributedString *)attStringWithText:(NSString *)text color:(UIColor *)color font:(UIFont *)font lineSpace:(CGFloat)lineSpace{ if (text.length == 0) return nil; NSMutableAttributedString *attM = [[NSMutableAttributedString alloc]initWithString:text]; NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc]init]; [paraStyle setLineSpacing:lineSpace]; [attM addAttribute:NSParagraphStyleAttributeName value:paraStyle range:NSMakeRange(0, text.length)]; if (color) { [attM addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, text.length)]; } if (font) { [attM addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, text.length)]; } return attM; } + (NSAttributedString *)attStringWithText:(NSString *)text lineSpace:(CGFloat)lineSpace { return [self attStringWithText:text color:nil font:nil lineSpace:lineSpace]; } + (CGSize)sizeOfAttributeString:(NSString*)text lineSpace:(CGFloat)lineSpace width:(CGFloat)width font:(UIFont *)font maxRow:(NSInteger)maxRow{ if (![FLStringHelper isValidString:text]) return CGSizeZero; NSMutableAttributedString *attM = [[NSMutableAttributedString alloc]initWithString:text]; NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc]init]; [paraStyle setLineSpacing:lineSpace]; [attM addAttribute:NSParagraphStyleAttributeName value:paraStyle range:NSMakeRange(0, text.length)]; [attM addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, text.length)]; return [attM boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size; } + (NSAttributedString *)attStringWithText:(NSString *)text color:(UIColor *)color font:(UIFont *)font subText:(NSString *)subText subColor:(UIColor *)subColor subFont:(UIFont *)subFont { NSMutableAttributedString *mutAttributedString = [[NSMutableAttributedString alloc] init]; if (text.length > 0 && color && font) { NSDictionary * attribtues = @{NSFontAttributeName:font, NSForegroundColorAttributeName:color}; NSAttributedString * attribtueString = [[NSAttributedString alloc] initWithString:text attributes:attribtues]; [mutAttributedString appendAttributedString:attribtueString]; } if (subText.length > 0 && subColor && subFont) { NSDictionary * attribtues = @{NSFontAttributeName:subFont, NSForegroundColorAttributeName:subColor, NSStrikethroughStyleAttributeName:@(NSUnderlineStyleSingle), NSStrikethroughColorAttributeName:subColor}; NSAttributedString * attribtueString = [[NSAttributedString alloc] initWithString:subText attributes:attribtues]; [mutAttributedString appendAttributedString:attribtueString]; } return mutAttributedString; } + (id)convertStringToJson:(NSString *)string { if (!string) { return nil; } NSError *error; NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *json = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &error]; if (!error) { return json; } return nil; } + (BOOL)isValidString:(NSString *)string{ if ([string isKindOfClass:[NSString class]] && string.length) { return YES; } return NO; } + (NSString *)jsonStrWithDict:(NSDictionary *)dict{ if (!dict) return nil; NSError *error; NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; #ifdef DEBUG if (error){ NSLog(@"json serialization fail error = %@", error.localizedDescription); } #endif if (data){ NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; return string; } return nil; } + (NSString *)convertToShortNumStr:(NSInteger)count{ if (count < 0) return nil; if (count < 10000){ return [NSString stringWithFormat:@"%ld", count]; }else{ NSInteger num = floor(count / 10000.0f); return [NSString stringWithFormat:@"%ld万", num]; } } @end