美文网首页
iOS 字符串NSString的一些扩展

iOS 字符串NSString的一些扩展

作者: 笑啥风云 | 来源:发表于2020-01-09 14:18 被阅读0次

判断是否是汉字

- (BOOL)isChinese
{
  NSString *match = @"(^[\u4e00-\u9fa5]+$)";
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
  return [predicate evaluateWithObject:self];
}

获取字符串中的所有URL

- (NSArray*)getURLs {
    NSError *error;
    //可以识别url的正则表达式
    NSString *regulaStr = @"((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\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    
    NSArray *arrayOfAllMatches = [regex matchesInString:self
                                                options:0
                                                  range:NSMakeRange(0, [self length])];
    
    //NSString *subStr;
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    
    for (NSTextCheckingResult *match in arrayOfAllMatches){
        NSString* substringForMatch;
        substringForMatch = [self substringWithRange:match.range];
        [arr addObject:substringForMatch];
    }
    return arr;
}
/**
 *  返回字符串所占用的尺寸
 *
 *  @param font    字体
 *  @param maxSize 最大尺寸
 */
- (CGRect)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize{
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil];
}
- (CGRect)sizeWithFont:(UIFont *)font maxasddSize:(CGSize)maxSize paragraphStyle:(NSParagraphStyle *) paragraphStyle
{
    NSDictionary *attrs = @{NSFontAttributeName : font,
                            NSParagraphStyleAttributeName:paragraphStyle
                            };
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil];
}

/*
*利用Emoji表情最终会被编码成Unicode,因此,
*只要知道Emoji表情的Unicode编码的范围,
*就可以判断用户是否输入了Emoji表情。
*/

+ (BOOL)stringContainsEmoji:(NSString *)string{
// 过滤所有表情。returnValue为NO表示不含有表情,YES表示含有表情
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        
        const unichar hs = [substring characterAtIndex:0];
        // surrogate pair
        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 {
            // non surrogate
            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;
            }
        }
    }];
    return returnValue;
}

//过滤 空格、换行符、制表符

- (NSString *)stringFilterSpaceAndOther{
    
    NSString *strUrl =  [self stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    strUrl = [strUrl stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    strUrl = [strUrl stringByReplacingOccurrencesOfString:@" " withString:@""];
    return strUrl;
    
}

// Json字符串转字典

- (NSDictionary *)stringWithJSONObject
{
    NSData *jsonData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败:%@",err);
        return nil;
    }
    return dic;
}

//去除小数点后面多余的0

+ (NSString *)removeFloatAllZero:(NSString *)string{
 NSString * testNumber = string;
    NSString * outNumber = [NSString stringWithFormat:@"%@",@(testNumber.floatValue)];
    //价格格式化显示
    NSNumberFormatter * formatter = [[NSNumberFormatter alloc]init];
    formatter.numberStyle = kCFNumberFormatterDecimalStyle;
    NSString * formatterString = [formatter stringFromNumber:[NSNumber numberWithFloat:[outNumber doubleValue]]];
    //获取要截取的字符串位置
    NSRange range = [formatterString rangeOfString:@"."];
    if (range.length >0 ) {
          NSString * result = [formatterString substringFromIndex:range.location];
          if (result.length >= 4) {
              formatterString = [formatterString substringToIndex:formatterString.length - 1];
          }
    }
    return formatterString;
}

//文件大小转换 b->

- (NSString *)convertFileSize{
 double convertedValue = [self doubleValue];
    int multiplyFactor = 0;
    NSArray *tokens = [NSArray arrayWithObjects:@"B",@"KB",@"MB",@"GB",@"TB",nil];
    while (convertedValue > 100) {

        convertedValue /= 1024;

        multiplyFactor++;

    }
    return [NSString stringWithFormat:@"%.2f %@",convertedValue, [tokens objectAtIndex:multiplyFactor]];
}

获取app名称、app版本号、app的build号

+ (NSString *)getProjectName{
    NSDictionary *infoDict= [[NSBundle mainBundle] infoDictionary];
    // app名称
    NSString *appName = [infoDict valueForKey:@"CFBundleDisplayName"];
    if (!appName) appName = [infoDict valueForKey:@"CFBundleName"];
    if (!appName) appName = [infoDict valueForKey:@"CFBundleExecutable"];
    return appName;
}
+ (NSString*)getProjectVersion{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app版本 NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version;
}
+ (NSString *)getProjectBuild{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app build版本
    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
    return app_build;
}

//转时间,XX:xx:xx,24小时内,常用于24小时的倒计时

+ (NSString *)JJTimeTransformFrom:(int)count{
     NSString *tempStr = nil;
     if (count >= 60) {
            int h = count / 3600;
            int d = count % 3600;
            int a = d / 60;
            int b = d % 60;
            tempStr = [NSString stringWithFormat:@"%02d:%02d:%02d",h,a,b];
    } else {
        tempStr = [NSString stringWithFormat:@"00:00:%02d",count];
    }
    return tempStr;
}

//获取汉字的拼音

- (NSString *)pinyin{
    NSMutableString *str = [self mutableCopy];
    CFStringTransform(( CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
    return [[str stringByReplacingOccurrencesOfString:@" " withString:@""] lowercaseString];
}
- (NSString *)transformToPinyin
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:self];
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    NSArray *pinyinArray = [str componentsSeparatedByString:@" "];
    NSMutableString *allString = [NSMutableString new];
    
    int count = 0;
    
    for (int  i = 0; i < pinyinArray.count; i++)
    {
        for(int i = 0; i < pinyinArray.count;i++)
        {
            if (i == count) {
                [allString appendString:@"#"];
                //区分第几个字母
            }
            [allString appendFormat:@"%@",pinyinArray[i]];
        }
        [allString appendString:@","];
        count ++;
    }
    NSMutableString *initialStr = [NSMutableString new];
    //拼音首字母
    for (NSString *s in pinyinArray)
    {
        if (s.length > 0)
        {
            [initialStr appendString:  [s substringToIndex:1]];
        }
    }
    [allString appendFormat:@"#%@",initialStr];
    [allString appendFormat:@",#%@",self];
    return allString;
}

相关文章

网友评论

      本文标题:iOS 字符串NSString的一些扩展

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