App开发流程之字符串处理工具类

时间:2023-01-31 23:07:01

记录字符串的处理,不是一个简单的工作。

NSString是代码中随处可见的类型,也是应用和处理繁多的对象,在此只记录需要常备的方法,并且加以说明。

#pragma mark -- 【计算字符串尺寸
+ (CGSize)getStringSizeWith:(NSString *)string attributes:(NSDictionary *)attributes;

+ (CGSize)getStringSizeWith:(NSString *)string attributes:(NSDictionary *)attributes maxWidth:(CGFloat)maxWidth;

+ (CGSize)getStringSizeWith:(NSString *)string attributes:(NSDictionary *)attributes maxHeight:(CGFloat)maxHeight;

+ (CGSize)getStringSizeWith:(NSString *)string font:(UIFont *)font paragraphStyle:(NSParagraphStyle *)paragraphStyle maxWidth:(CGFloat)maxWidth;

+ (CGSize)getStringSizeWith:(NSString *)string font:(UIFont *)font lineHeight:(CGFloat)lineHeight maxWidth:(CGFloat)maxWidth;

+ (CGSize)getStringSizeWith:(NSString *)string font:(UIFont *)font;

+ (CGSize)getStringSizeWith:(NSString *)string font:(UIFont *)font maxWidth:(CGFloat)maxWidth;

+ (CGSize)getStringSizeWith:(NSString *)string font:(UIFont *)font maxHeight:(CGFloat)maxHeight;
#pragma mark -- 】计算字符串尺寸

#pragma mark -- 【生成属性字符串
+ (NSAttributedString *)getAttributedStringWithString:(NSString *)string font:(UIFont *)font color:(UIColor *)color lineHeight:(CGFloat)lineHeight maxWidth:(CGFloat)maxWidth;

+ (NSAttributedString *)getAttributedStringWithString:(NSString *)string font:(UIFont *)font color:(UIColor *)color paragraphStyle:(NSParagraphStyle *)paragraphStyle maxWidth:(CGFloat)maxWidth;
#pragma mark -- 】生成属性字符串

#pragma mark -- 【处理时间字符串
+ (NSString *)getCurrentDateString;

+ (NSString *)getCurrentDateStringWithFormat:(NSString *)dateFormat;

+ (NSString *)getDateStringWithTimeInterval:(NSTimeInterval)timeInterval;

+ (NSString *)getDateStringWithTimeInterval:(NSTimeInterval)timeInterval dateFormat:(NSString *)dateFormat;

+ (NSTimeInterval)getTimeIntervalWithDateString:(NSString *)dateString;

+ (NSDateComponents *)getDateComponentsWithDateString:(NSString *)dateString;

+ (NSDateComponents *)getDateComponentsWithTimeInterval:(NSTimeInterval)timeInterval;

+ (NSString *)getContentPublishedTimeStringWithDateString:(NSString *)dateString;
#pragma mark -- 】处理时间字符串

#pragma mark -- 【处理网络请求相关字符串
+ (NSString *)getSafeDecodeStringFromJsonValue:(NSString *)jsonValue;

/**
 *  被解析的url字符串格式为:xxxxxx?a=xxx&b=xxx
 *
 *  @param urlString urlString description
 *
 *  @return return value description
 */
+ (NSDictionary *)getParametersDictionaryWithUrlString:(NSString *)urlString;

/**
 *  被解析的url字符串格式为:xxxxxx/realname_320x640.png(/jpg)
 *
 *  @param urlString urlString description
 *
 *  @return return value description
 */
+ (CGSize)getImageOriginalSizeWithUrlString:(NSString *)urlString;

+ (CGSize)getImageShowSizeWithUrlString:(NSString *)urlString maxWidth:(NSInteger)maxWidth;

/**
 *  被解析的url字符串格式为:xxxxxx/realname_320x640.png(/jpg)
 *
 *  @param originalUrlString originalUrlString description
 *  @param newWidth          newWidth description
 *
 *  @return 在原urlString后增加类似"?act=resize&x=320",用于服务器裁剪尺寸
 */
+ (NSString *)getImageResizedUrlStringWithOriginalUrlString:(NSString *)originalUrlString newWidth:(NSInteger)newWidth;
#pragma mark -- 】处理网络请求相关字符串

#pragma mark -- 其他功能方法
/**
 *  获取字符串的字节长度(一个汉字占两个字节长度)
 *
 *  @param string string description
 *
 *  @return return value description
 */
+ (NSInteger)getBytesLengthWithString:(NSString *)string;

/**
 *  验证手机号是否合理
 *
 *  @param phoneNum phoneNum description
 *
 *  @return return value description
 */
+ (BOOL)isValidatedMobliePhoneNum:(NSString *)phoneNum;

+ (void)printAllCurrentSupportedFonts;

+ (NSString *)getDeviceVersion;

+ (NSString *)getAppShortVersion;

+ (NSString *)getAppBundleVersion;

 

说明:

1.计算字符串尺寸的方法,sizeWithFont系列方法已经被废物,建议改为boundingRectWithSize方法;NSAttributedString也有boundingRectWithSize方法,如果已知属性字符串可以直接使用。请查看UIKit/NSStringDrawing.h中NSString和NSAttributedString的扩展方法

 

+ (CGSize)getStringSizeWith:(NSString *)string attributes:(NSDictionary *)attributes
{
    CGSize size = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    
    return size;
}

 

3.生成属性字符串的方法中,NSMutableParagraphStyle的对象用于设置段落属性(行高、行间距、段落间距、对齐、书写方向、首行缩进、行首缩进、行尾缩进),请查看UIKit/NSParagraphStyle.h

+ (NSAttributedString *)getAttributedStringWithString:(NSString *)string font:(UIFont *)font color:(UIColor *)color lineHeight:(CGFloat)lineHeight maxWidth:(CGFloat)maxWidth
{
    CGFloat perLineHeight = [StringHelper getStringSizeWith:@"内容" font:font].height;
    CGFloat lineSpacing = (lineHeight - perLineHeight)/2.5;//2.5是在实际应用中,调校的值
    perLineHeight = lineHeight - lineSpacing;
    
    //设置文字段落
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineHeightMultiple = perLineHeight;
    paragraphStyle.maximumLineHeight = perLineHeight;
    paragraphStyle.minimumLineHeight = perLineHeight;
    paragraphStyle.lineBreakMode = commonLineBreakMode;
    paragraphStyle.lineSpacing = lineSpacing;//行间距
    paragraphStyle.paragraphSpacing = 0;//段间距
    paragraphStyle.alignment = commonTextAlignment;

    return [self getAttributedStringWithString:string font:font color:color paragraphStyle:paragraphStyle maxWidth:maxWidth];
}

+ (NSAttributedString *)getAttributedStringWithString:(NSString *)string font:(UIFont *)font color:(UIColor *)color paragraphStyle:(NSParagraphStyle *)paragraphStyle maxWidth:(CGFloat)maxWidth
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:font forKey:NSFontAttributeName];
    [dic setObject:color forKey:NSForegroundColorAttributeName];
    [dic setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
    
    NSAttributedString* attributedString;
    
    if (string == nil) {
        attributedString = [[NSAttributedString alloc] initWithString:@" " attributes:dic];
    }else{
        attributedString = [[NSAttributedString alloc] initWithString:string attributes:dic];
    }
    
    return attributedString;
}

 

4.NSFontAttributeName、NSForegroundColorAttributeName、NSParagraphStyleAttributeName为NSAttributedString常用属性键值,更多查看UIKit/NSAttributedString.h

5.转换时间字符串,需要记录一下常用时间格式占位字符:

#pragma mark -- 时间格式占位符
//G:        公元时代,例如AD公元
//yy:       年的后2位
//yyyy:     完整年
//MM:       月,显示为1-12,带前置0
//MMM:      月,显示为英文月份简写,如 Jan
//MMMM:     月,显示为英文月份全称,如 Janualy
//dd:       日,2位数表示,如02
//d:        日,1-2位显示,如2,无前置0
//EEE:      简写星期几,如Sun
//EEEE:     全写星期几,如Sunday
//aa:       上下午,AM/PM
//H:        时,24小时制,0-23
//HH:       时,24小时制,带前置0
//h:        时,12小时制,无前置0
//hh:       时,12小时制,带前置0
//m:        分,1-2位
//mm:       分,2位,带前置0
//s:        秒,1-2位
//ss:       秒,2位,带前置0
//S:        毫秒
//Z:        GMT(时区)
+ (NSString *)getCurrentDateString
{
    return [self getCurrentDateStringWithFormat:@"yyyy-MM-dd HH:mm:ss"];
}

+ (NSString *)getCurrentDateStringWithFormat:(NSString *)dateFormat
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormat];
    NSDate *currentDate = [NSDate date];
    NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
    
    return currentDateString;
}

 

6.getDateComponentsWithDateString方法用于得到日期组成对象,实现代码、测试代码、输入log如下:

+ (NSDateComponents *)getDateComponentsWithDateString:(NSString *)dateString
{
    NSTimeInterval timeInterval = [self getTimeIntervalWithDateString:dateString];
    
    return [self getDateComponentsWithTimeInterval:timeInterval];
}

+ (NSDateComponents *)getDateComponentsWithTimeInterval:(NSTimeInterval)timeInterval
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSCalendarUnit unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | NSCalendarUnitWeekOfMonth  | NSCalendarUnitWeekOfYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *components = [calendar components:unitFlags fromDate:date];
    
    return components;
}
    NSDateComponents *components = [StringHelper getDateComponentsWithDateString:@"2016-09-12 12:56:10"];
    LOG(@"%@", components);
    
    components = [StringHelper getDateComponentsWithDateString:@"2016-09-11 12:56:10"];
    LOG(@"%@", components);

    components = [StringHelper getDateComponentsWithDateString:@"2016-09-10 12:56:10"];
    LOG(@"%@", components);
2016-09-12 13:02:12.283 base[14229:1700476] <NSDateComponents: 0x7fb0f9570770>
    Calendar Year: 2016
    Month: 9
    Leap month: no
    Day: 12
    Hour: 12
    Minute: 56
    Second: 10
    Week of Year: 38
    Week of Month: 3
    Weekday: 2
2016-09-12 13:02:15.600 base[14229:1700476] <NSDateComponents: 0x7fb0f961e760>
    Calendar Year: 2016
    Month: 9
    Leap month: no
    Day: 11
    Hour: 12
    Minute: 56
    Second: 10
    Week of Year: 38
    Week of Month: 3
    Weekday: 1
2016-09-12 13:02:15.601 base[14229:1700476] <NSDateComponents: 0x7fb0f94b6620>
    Calendar Year: 2016
    Month: 9
    Leap month: no
    Day: 10
    Hour: 12
    Minute: 56
    Second: 10
    Week of Year: 37
    Week of Month: 2
    Weekday: 7

需要注意的是,Weekday“一”为“周日”,“七”为“周六”,按照西方习俗;Week of Month表示本月第几周;Week of Year表示今年第几周。

7.getDeviceVersion方法更新了iPhone 7和iPhone 7 Plus的设备版本判断,详情参考:https://www.theiphonewiki.com/wiki/Models

8.随便一提,如果在新增的NSObject类中,无法使用CGFloat、CGPoint之类的类型,是因为没有引用这些类型所在的头文件,在预编译头文件中引用即可:#import <UIKit/UIKit.h>

 

base项目已更新:git@github.com:ALongWay/base.git