博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS - NSString 封装
阅读量:5875 次
发布时间:2019-06-19

本文共 5985 字,大约阅读时间需要 19 分钟。

在实际项目开发过程中,发现字符串使用频率还是非常高的,NSString提供了很多相关的API,但是在开发过程中发现很多业务功能都是相同的。因此根据在开发过程中遇到的字符串使用场景,进行了简单封装。具体代码如下:

NSString+Category.h 代码:

////  NSString+Category.h//  myApplication////  Created by xujinzhong on 2018/3/13.//  Copyright © 2018年 xujinzhong. All rights reserved.//#import 
@interface NSString (Category)- (BOOL)isBlank;- (BOOL)isValid;- (NSString *)removeWhiteSpacesFromString;- (NSUInteger)countNumberOfWords;- (BOOL)containsString:(NSString *)subString;- (BOOL)isBeginsWith:(NSString *)string;- (BOOL)isEndssWith:(NSString *)string;- (NSString *)replaceCharcter:(NSString *)olderChar withCharcter:(NSString *)newerChar;- (NSString*)getSubstringFrom:(NSInteger)begin to:(NSInteger)end;- (NSString *)addString:(NSString *)string;- (NSString *)removeSubString:(NSString *)subString;- (BOOL)containsOnlyLetters;- (BOOL)containsOnlyNumbers;- (BOOL)containsOnlyNumbersAndLetters;- (BOOL)isInThisarray:(NSArray*)array;+ (NSString *)getStringFromArray:(NSArray *)array;- (NSArray *)getArray;+ (NSString *)getMyApplicationVersion;+ (NSString *)getMyApplicationName;- (NSData *)convertToData;+ (NSString *)getStringFromData:(NSData *)data;- (BOOL)isValidEmail;- (BOOL)isVAlidPhoneNumber;- (BOOL)isValidUrl;@end

NSString+Category.m 代码:

////  NSString+Category.m//  myApplication////  Created by xujinzhong on 2018/3/13.//  Copyright © 2018年 xujinzhong. All rights reserved.//#import "NSString+Category.h"@implementation NSString (Category)//字符串是否为空-(BOOL)isBlank{    return ([[self removeWhiteSpacesFromString] isEqualToString:@""]) ? YES : NO;}//字符串为空或nil-(BOOL)isValid{    return ([[self removeWhiteSpacesFromString] isEqualToString:@""] || self == nil || [self isEqualToString:@"(null)"]) ? NO :YES;}//在字符串中删除空格- (NSString *)removeWhiteSpacesFromString{    NSString *trimmedString = [self stringByTrimmingCharactersInSet:                               [NSCharacterSet whitespaceAndNewlineCharacterSet]];    return trimmedString;}//字符串中包含单词数- (NSUInteger)countNumberOfWords{    NSScanner *scanner = [NSScanner scannerWithString:self];    NSCharacterSet *whiteSpace = [NSCharacterSet whitespaceAndNewlineCharacterSet];        NSUInteger count = 0;    while ([scanner scanUpToCharactersFromSet: whiteSpace  intoString: nil]) {        count++;    }        return count;}// 字符串中是否包含子字符串- (BOOL)containsString:(NSString *)subString{    return ([self rangeOfString:subString].location == NSNotFound) ? NO : YES;}// 字符串从给定的字符串开始- (BOOL)isBeginsWith:(NSString *)string{    return ([self hasPrefix:string]) ? YES : NO;}// 字符串以给定的字符串结束- (BOOL)isEndssWith:(NSString *)string{    return ([self hasSuffix:string]) ? YES : NO;}// 用新字符替换字符串中的特定字符- (NSString *)replaceCharcter:(NSString *)olderChar withCharcter:(NSString *)newerChar{    return  [self stringByReplacingOccurrencesOfString:olderChar withString:newerChar];}// 从特定的位置获取子字符串,以使其正确- (NSString*)getSubstringFrom:(NSInteger)begin to:(NSInteger)end{    NSRange r;    r.location = begin;    r.length = end - begin;    return [self substringWithRange:r];}// 将子字符串添加到主字符串- (NSString *)addString:(NSString *)string{    if(!string || string.length == 0)        return self;        return [self stringByAppendingString:string];}// 从字符串中删除指定字符串-(NSString *)removeSubString:(NSString *)subString{    if ([self containsString:subString])    {        NSRange range = [self rangeOfString:subString];        return  [self stringByReplacingCharactersInRange:range withString:@""];    }    return self;}// 字符串只包含字母- (BOOL)containsOnlyLetters{    NSCharacterSet *letterCharacterset = [[NSCharacterSet letterCharacterSet] invertedSet];    return ([self rangeOfCharacterFromSet:letterCharacterset].location == NSNotFound);}// 字符串只包含数字- (BOOL)containsOnlyNumbers{    NSCharacterSet *numbersCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];    return ([self rangeOfCharacterFromSet:numbersCharacterSet].location == NSNotFound);}// 字符串中包含数字和字母- (BOOL)containsOnlyNumbersAndLetters{    NSCharacterSet *numAndLetterCharSet = [[NSCharacterSet alphanumericCharacterSet] invertedSet];    return ([self rangeOfCharacterFromSet:numAndLetterCharSet].location == NSNotFound);}// 字符串包含在数组中- (BOOL)isInThisarray:(NSArray*)array{    for(NSString *string in array) {        if([self isEqualToString:string]) {            return YES;        }    }    return NO;}// 数组转换为字符串+ (NSString *)getStringFromArray:(NSArray *)array{    return [array componentsJoinedByString:@" "];}// 字符串转换为数组- (NSArray *)getArray{    return [self componentsSeparatedByString:@" "];}// 获取应用程序版本+ (NSString *)getMyApplicationVersion{    NSDictionary *info = [[NSBundle mainBundle] infoDictionary];    NSString *version = [info objectForKey:@"CFBundleVersion"];    return version;}// 获取应用程序名称+ (NSString *)getMyApplicationName{    NSDictionary *info = [[NSBundle mainBundle] infoDictionary];    NSString *name = [info objectForKey:@"CFBundleDisplayName"];    return name;}// 字符串转换为NSData- (NSData *)convertToData{    return [self dataUsingEncoding:NSUTF8StringEncoding];}// NSData转换为字符串+ (NSString *)getStringFromData:(NSData *)data{    return [[NSString alloc] initWithData:data                                 encoding:NSUTF8StringEncoding];}// 是否为邮件格式- (BOOL)isValidEmail{    NSString *regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";    NSPredicate *emailTestPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];    return [emailTestPredicate evaluateWithObject:self];}// 是否为电话格式- (BOOL)isVAlidPhoneNumber{    NSString *regex = @"[235689][0-9]{6}([0-9]{3})?";    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];    return [test evaluateWithObject:self];}// 是否为URL格式- (BOOL)isValidUrl{    NSString *regex =@"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];    return [urlTest evaluateWithObject:self];}@end

 

转载于:https://www.cnblogs.com/xujinzhong/p/8555163.html

你可能感兴趣的文章
VS 2015 GIT操作使用说明
查看>>
上海办理房产税变更
查看>>
每天一个linux命令(52):scp命令
查看>>
CMOS Sensor Interface(CSI)
查看>>
linq中的contains条件
查看>>
HDU 5590 ZYB's Biology 水题
查看>>
memcached 分布式聚类算法
查看>>
言未及之而言,谓之躁;言及之而不言,谓之隐;未见颜色而言,谓之瞽(gǔ)...
查看>>
MYSQL查询一周内的数据(最近7天的)
查看>>
Redis的缓存策略和主键失效机制
查看>>
禁止body滚动允许div滚动防微信露底
查看>>
Xtreme8.0 - Kabloom dp
查看>>
jquery css3问卷答题卡翻页动画效果
查看>>
MDK5.00中*** error 65: access violation at 0xFFFFFFFC : no 'write' permission的一种解决方法
查看>>
Android 集成支付宝支付详解
查看>>
SQL分布式查询、跨数据库查询
查看>>
C#------连接SQLServer和MySQL字符串
查看>>
Arcgis Licensemanager 不能启动的原因之一(转载)
查看>>
(原)Android在子线程用handler发送的消息,主线程是怎么loop到的?
查看>>
$digest already in progress 解决办法——续
查看>>