NSString

NSString 《笔记篇章》

2017-08-23  本文已影响21人  失忆的程序员

上传 :NSDictionary / NSArray

// dic

- (NSString *)xpf_dic_jsonStringWithPrettyPrint:(BOOL)prettyPrint {

NSError *error;

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:(NSJSONWritingOptions)(prettyPrint ? NSJSONWritingPrettyPrinted : 0) error:&error];

if (! jsonData) {

NSLog(@" : error: %@", error.localizedDescription);

return @"{}";

} else {

return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

}

}

// ary

- (NSString *)xpf_ary_jsonStringWithPrettyPrint:(BOOL)prettyPrint {

NSError *error;

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:(NSJSONWritingOptions)(prettyPrint ? NSJSONWritingPrettyPrinted : 0) error:&error];

if (! jsonData) {

NSLog(@" : error: %@", error.localizedDescription);

return @"[]";

} else {

return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

}

}

/*!

* @brief 把格式化的JSON格式的字符串转换成字典

* @param jsonString JSON格式的字符串

* @return 返回字典

*/

json格式字符串转字典:

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {

if (jsonString == nil) {

return nil;

}

NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSError *err;

NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData

options:NSJSONReadingMutableContainers

error:&err];

if(err) {

NSLog(@"json解析失败:%@",err);

return nil;

}

return dic;

}

字典转json格式字符串:

+ (NSString*)dictionaryToJson:(NSDictionary *)dic

{

NSError *parseError = nil;

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];

return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

}

NSJSONWritingPrettyPrinted  是有换位符的。

如果NSJSONWritingPrettyPrinted 是nil 的话 返回的数据是没有 换位符的

上传字符串

//To convert a NSDictionary to a NSString:

NSError*err;

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary options:0error:&err];

NSString *myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

// =======

NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];

[contentDictionary setValue:@"a" forKey:@"b"];

[contentDictionary setValue:@"c" forKey:@"d"];

NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];

NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

参考:https://stackoverflow.com/questions/6368867/generate-json-string-from-nsdictionary-in-ios

一、对于字符串的操作

截取字符串

NSString*string =@"abcdefghijklmn";

string = [string substringToIndex:7];//截取掉下标7之后的字符串

NSLog(@"截取的值为:%@",string);//输出结果为:ijkimn

NSString*string =@"abcdefghijklmn";

[string substringFromIndex:2];//截取掉下标2之前的字符串

NSLog(@"截取的值为:%@",string);//输出结果为:abc

NSString*string =@"abcdefghijklmn";

string = [string substringWithRange:NSMakeRange(4,2)];//截取下标为4范围为2的字符串

NSLog(@"截取的值为:%@",string);//输出结果为:ef

匹配字符串

NSString*string =@"abcdefghijklmn";

NSRange range = [string rangeOfString:@"f"];//匹配得到的下标

NSLog(@"range:%@",NSStringFromRange(range));//输出结果为range:{5,1}

string = [string substringWithRange:range];//截取范围类的字符串

NSLog(@"截取的值为:%@",string);//输出结果为:f

分隔字符串

NSString*string =@"abcdeAfghijk";

NSArray *array = [string componentsSeparatedByString:@"A"]; //从字符A中分隔成2个元素的数组

NSLog(@"array:%@",array); //结果是abcde和fghijk

替换字符串

NSString*string = @"abcdefghljklmn";

string = [string stringByReplacingOccurrencesOfString:@"abc" withString:@"123"];

NSLog(@"string:%@",string);//结果为:123defghljklmn

二、有时候我们需要对于字符串是否为空进行判断

在网上搜集到的判断string为空的方法

string.length == 0 || [string isEqualToString:@""] || string == nil || string == NULL || [string isEqual:[NSNull null]] || [string isEqualTostring:@“(null)”] || [string isEqual:@"(null)"] || [string isKindOfClass:[NSNull class]] || [[string stringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceAndNewlineCharacterSet]] length]==0

三、字符串可以比较大小

NSString*a =@"asd";

NSString*b =@"dfs";

NSComparisonResultresult = [stra compare:strb];

if(result ==NSOrderedSame) {

//NSLog(@"a = b");

}elseif(result ==NSOrderedAscending) {

//NSLog(@"a < b");

}else{

//NSLog(@"a > b");

}

三、常用扩展功能(类别扩展)

md5

- (NSString*)md5HexDigest

{

constchar* str = [selfUTF8String];unsignedcharresult[CC_MD5_DIGEST_LENGTH];

CC_MD5(str, strlen(str), result);

NSMutableString*ret = [NSMutableStringstringWithCapacity:CC_MD5_DIGEST_LENGTH];

for(int i =0; i

[ret appendFormat:@"%02X",result[i]];

}returnret;

}

urlEncode

- (NSString*)stringEncode {NSString*encodedString = (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self,NULL,CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), kCFStringEncodingUTF8));returnencodedString;

}

- (NSString*)stringDecode {NSString*result = [(NSString*)selfstringByReplacingOccurrencesOfString:@"+"withString:@" "];

result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];returnresult;

}

sizeFromFont

- (CGSize)boundingRectWithSize:(CGSize)size

withTextFont:(UIFont*)font {if([selfisEqualToString:@""]) {returnCGSizeMake(0,0);

}NSMutableParagraphStyle*paragraphStyle = [[NSMutableParagraphStylealloc] init];

paragraphStyle.lineBreakMode =NSLineBreakByWordWrapping;

paragraphStyle.lineSpacing =0;NSDictionary*attributes = @{NSFontAttributeName:font,NSParagraphStyleAttributeName:paragraphStyle.copy};return[selfboundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOriginattributes:attributes context:nil].size;

}

是否是邮箱格式

- (BOOL)isEmail

{

NSString*emailRegEx =@"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"@"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"@"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"@"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"@"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"@"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"@"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";

NSPredicate*regExPredicate = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", emailRegEx];return[regExPredicate evaluateWithObject:[selflowercaseString]];

}

Base64

- (NSString*)base64 {

// Create NSData object

NSData*nsdata = [selfdataUsingEncoding:NSUTF8StringEncoding];

// Get NSString from NSData object in Base64

NSString*base64Encoded = [nsdata base64EncodedStringWithOptions:0];// Print the Base64 encoded stringreturnbase64Encoded;

}

- (NSString*)base64Decoded {

// NSData from the Base64 encoded str

NSData*nsdataFromBase64String = [[NSDataalloc] initWithBase64EncodedString:selfoptions:0];

// Decoded NSString from the NSData

NSString*base64Decoded = [[NSStringalloc] initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];returnbase64Decoded;

}

上一篇下一篇

猜你喜欢

热点阅读