iOS技术文档No.18 AppKit_NSString(二 常

2017-07-24  本文已影响8人  孤独雪域

NSString过滤特殊字符

// 定义一个特殊字符的集合 
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString: @"@/:;()¥「」"、[]{}#%-*+=_\\|~<>$€^•'@#$%^&*()_+'\""]; 

// 过滤字符串的特殊字符 
NSString *newString = [trimString stringByTrimmingCharactersInSet:set];

去除所有空格

[str stringByReplacingOccurrencesOfString:@" " withString:@""];

去除收尾的空格

[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
- (NSString *)uppercaseString; // 全部字符转为大写字母
- (NSString *)lowercaseString;// 全部字符转为小写字母

复制字符串到剪贴板

UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = self.label.text;

处理标签字符串中的空格,换行,/t(制表符)等

- (NSString *)replaceStringWithString :(NSMutableString *)string{
 NSString *string1 = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""] ; 
NSString *string2 = [string1 stringByReplacingOccurrencesOfString:@" " withString:@""] ; 
NSString *string3 = [string2 stringByReplacingOccurrencesOfString:@"\r" withString:@""] ; 
NSString *string4 = [string3 stringByReplacingOccurrencesOfString:@"\t" withString:@""] ; 
return string4 ;
}

UIImage与字符串互转

//字符串转图片
-(UIImage *)Base64StrToUIImage:(NSString *)_encodedImageStr{ 
NSData *_decodedImageData = [[NSData alloc] initWithBase64Encoding:_encodedImageStr]; 
UIImage *_decodedImage = [UIImage imageWithData:_decodedImageData]; 
return _decodedImage;
}
//图片转字符串
-(NSString *)UIImageToBase64Str:(UIImage *) image{ 
NSData *data = UIImageJPEGRepresentation(image, 1.0f); 
NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
 return encodedImageStr;
}

根据汉字字符串获取该字符串的拼音然后取得首字母

分享资源 汉字转换为 拼音 获取首字母
//获取拼音首字母(传入汉字字符串, 返回大写拼音首字母)/* 
- (NSString *)firstCharactor:(NSString *)aString { 
//转成了可变字符串
 NSMutableString *str = [NSMutableString stringWithString:aString]; 
//先转换为带声调的拼音 
CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO); 
//再转换为不带声调的拼音 
CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO); 
//转化为大写拼音
 NSString *pinYin = [str capitalizedString];
 //获取并返回首字母
 return [pinYin substringToIndex:1]; 
} 
*/
NSString *string = @"简书" ;
if ([string length]){ 
NSMutableString *mutableString = [NSMutableString stringWithString:string] ; 
/** * 由于此方法是在coreFoundation框架下,咱们平时所使用的类型都是Foundation框架下的,所以需要转换类型. 
* * @param string#> string 所需要转换的原字符#> 
* @param range#> range 所需要转换字符的范围.
如果为0或者是NULL意思是所有字符都转换#> 
* @param transform#> transform 转换方式#>
 * @param reverse#> reverse 如果为YES,返回原字符串;如果为NO,返回转换之后的字符串#> 
* * @return return value description */ 
// 将所有非英文的字符转换为拉丁字母,并且带声调和重音标识 
// __bridge :只改变当前对象的类型,但是不改变对象内存的管理权限 
CFStringTransform((__bridge CFMutableStringRef)mutableString , 0,kCFStringTransformToLatin , NO) ; 
// 去掉声调
 CFStringTransform((__bridge CFMutableStringRef)mutableString , 0,kCFStringTransformStripDiacritics , NO) ; 
// 每个单词的首字母大写 后再截取字符串
 NSString *str = [[mutableString capitalizedString] substringToIndex:1];}

验证身份证号码

//验证身份证号码
- (BOOL)checkIdentityCardNo:(NSString*)cardNo{ 
if (cardNo.length != 18) { 
return NO; 
}
 NSArray* codeArray = [NSArray arrayWithObjects:@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6",@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2", nil]; 
NSDictionary* checkCodeDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"0",@"X",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2", nil] forKeys:[NSArray arrayWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]];
 NSScanner* scan = [NSScanner scannerWithString:[cardNo substringToIndex:17]]; 
int val;
 BOOL isNum = [scan scanInt:&val] && [scan isAtEnd];
 if (!isNum) { 
return NO; 
} 
int sumValue = 0; 
for (int i =0; i<17; i++) { 
sumValue+=[[cardNo substringWithRange:NSMakeRange(i , 1) ] intValue]* [[codeArray objectAtIndex:i] intValue];
 } 
NSString* strlast = [checkCodeDic objectForKey:[NSString stringWithFormat:@"%d",sumValue%11]]; 
if ([strlast isEqualToString: [[cardNo substringWithRange:NSMakeRange(17, 1)]uppercaseString]]) {
 return YES;
 } 
return NO;
}

判断手机号码格式是否正确

//判断手机号码格式是否正确
+ (BOOL)valiMobile:(NSString *)mobile{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];

        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}

判断邮箱格式是否正确

//利用正则表达式验证
+ (BOOL)isAvailableEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

获取iOS路径的方法

获取家目录路径的函数
NSString *homeDir = NSHomeDirectory();

获取Documents目录路径的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];

获取Documents目录路径的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];

获取tmp目录路径的方法:
NSString *tmpDir = NSTemporaryDirectory();

获取设备IP地址

需要引入下头文件:

#import <ifaddrs.h>
#import <arpa/inet.h>

代码:

//获取设备 IP 地址
+ (NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    success = getifaddrs(&interfaces);
    if (success == 0) {
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    freeifaddrs(interfaces);
    return address;
}

获取WiFi信息

需要引入头文件

#import <SystemConfiguration/CaptiveNetwork.h>

代码:

//获取 WiFi 信息
- (NSDictionary *)fetchSSIDInfo {
    NSArray *ifs = (__bridge_transfer NSArray *)CNCopySupportedInterfaces();
    if (!ifs) {
        return nil;
    }
    NSDictionary *info = nil;
    for (NSString *ifnam in ifs) {
        info = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        if (info && [info count]) { break; }
    }
    return info;
}

获取广播地址、本机地址、子网掩码、端口信息

#import <ifaddrs.h>
#import <arpa/inet.h>


//获取广播地址、本机地址、子网掩码、端口信息
- (NSMutableDictionary *)getLocalInfoForCurrentWiFi {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        //*/
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    //广播地址
                    NSString *broadcast = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)];
                    if (broadcast) {
                        [dict setObject:broadcast forKey:@"broadcast"];
                    }
                    //                    NSLog(@"broadcast address--%@",broadcast);
                    //本机地址
                    NSString *localIp = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                    if (localIp) {
                        [dict setObject:localIp forKey:@"localIp"];
                    }
                    //                    NSLog(@"local device ip--%@",localIp);
                    //子网掩码地址
                    NSString *netmask = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)];
                    if (netmask) {
                        [dict setObject:netmask forKey:@"netmask"];
                    }
                    //                    NSLog(@"netmask--%@",netmask);
                    //--en0 端口地址
                    NSString *interface = [NSString stringWithUTF8String:temp_addr->ifa_name];
                    if (interface) {
                        [dict setObject:interface forKey:@"interface"];
                    }
                    //                    NSLog(@"interface--%@",interface);
                    return dict;
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return dict;
}

获取字符串(或汉字)首字母

//获取字符串(或汉字)首字母
+ (NSString *)firstCharacterWithString:(NSString *)string{
    NSMutableString *str = [NSMutableString stringWithString:string];
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
    NSString *pingyin = [str capitalizedString];
    return [pingyin substringToIndex:1];
}

将字符串数组按照元素首字母顺序进行排序进行排序分组

//将字符串数组按照元素首字母顺序进行排序分组
+ (NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array{
    if (array.count == 0) {
        return nil;
    }
    for (id obj in array) {
        if (![obj isKindOfClass:[NSString class]]) {
            return nil;
        }
    }
    UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation];
    NSMutableArray *objects = [NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count];
    //创建27个分组数组
    for (int i = 0; i < indexedCollation.sectionTitles.count; i++) {
        NSMutableArray *obj = [NSMutableArray array];
        [objects addObject:obj];
    }
    NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count];
    //按字母顺序进行分组
    NSInteger lastIndex = -1;
    for (int i = 0; i < array.count; i++) {
        NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)];
        [[objects objectAtIndex:index] addObject:array[i]];
        lastIndex = index;
    }
    //去掉空数组
    for (int i = 0; i < objects.count; i++) {
        NSMutableArray *obj = objects[i];
        if (obj.count == 0) {
            [objects removeObject:obj];
        }
    }
    //获取索引字母
    for (NSMutableArray *obj in objects) {
        NSString *str = obj[0];
        NSString *key = [self firstCharacterWithString:str];
        [keys addObject:key];
    }
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:objects forKey:keys];
    return dic;
}

//获取字符串(或汉字)首字母
+ (NSString *)firstCharacterWithString:(NSString *)string{
    NSMutableString *str = [NSMutableString stringWithString:string];
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
    NSString *pingyin = [str capitalizedString];
    return [pingyin substringToIndex:1];
}

使用如下:

NSArray *arr = @[@"guangzhou", @"shanghai", @"北京", @"henan", @"hainan"];
NSDictionary *dic = [Utilities dictionaryOrderByCharacterWithOriginalArray:arr];
NSLog(@"\n\ndic: %@", dic);

输出结果如下:


输出结果

判断字符串中是否含空格

+ (BOOL)isHaveSpaceInString:(NSString *)string{
    NSRange _range = [string rangeOfString:@" "];
    if (_range.location != NSNotFound) {
        return YES;
    }else {
        return NO;
    }
}

判断字符串中是否含有某个字符串

+ (BOOL)isHaveSpaceInString:(NSString *)string{
    NSRange _range = [string rangeOfString:@" "];
    if (_range.location != NSNotFound) {
        return YES;
    }else {
        return NO;
    }
}

判断字符串中是否含有中文

+ (BOOL)isHaveChineseInString:(NSString *)string{
    for(NSInteger i = 0; i < [string length]; i++){
        int a = [string characterAtIndex:i];
        if (a > 0x4e00 && a < 0x9fff) {
            return YES;
        }
    }
    return NO;
}

判断字符串是否全部为数字

+ (BOOL)isAllNum:(NSString *)string{
    unichar c;
    for (int i=0; i<string.length; i++) {
        c=[string characterAtIndex:i];
        if (!isdigit(c)) {
            return NO;
        }
    }
    return YES;
}

将字典对象转换为JSON字符串

+ (NSString *)jsonPrettyStringEncoded:(NSDictionary *)dictionary{
    if ([NSJSONSerialization isValidJSONObject:dictionary ]) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
        if (!error) {
            NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            return json;
        }
    }
    return nil;
}

将数组对象转换为JSON字符串

+ (NSString *)jsonPrettyStringEncoded:(NSArray *)array{
    if ([NSJSONSerialization isValidJSONObject:array]) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
        if (!error) {
            NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            return json;
        }
    }
    return nil;
}

上一篇下一篇

猜你喜欢

热点阅读