拼接字符串
NSString* string; NSString* string1, string2; //方法1. string = [NSString initWithFormat:@"%@,%@", string1, string2 ]; //方法2.(常用) string = [string1 stringByAppendingString:string2]; //方法3 . string = [string stringByAppendingFormat:@"%@,%@",string1, string2];
清除字符串 首尾空格及换行符
//清除首尾空格 //定义宏 #define allTrim(object) [object stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] //调用宏 NSString *emptyString = @" "; if ([allTrim( emptyString ) length] == 0 ) { NSLog(@"Is empty!"); } //清除所有空格(替换操作) NSString *strUrl = [urlString stringByReplacingOccurrencesOfString:@" " withString:@""]; //清除换行字符 headerData = [headerData stringByReplacingOccurrencesOfString:@" " withString:@""]; headerData = [headerData stringByReplacingOccurrencesOfString:@" " withString:@""];
判断空值处理 (null)与 <null>
//见过最好的解决方法之一, 改进的内联函数,源自Git Hub // Check if the "thing" pass'd is empty static inline BOOL isEmpty(id thing) { return thing == nil || [thing isKindOfClass:[NSNull class]] || ([thing respondsToSelector:@selector(length)] && [(NSData *)thing length] == 0) || ([thing respondsToSelector:@selector(count)] && [(NSArray *)thing count] == 0); }
//判断UITextField.text是否为空 用户未进行任何输入的情况下为nil. (yourTextField.text 在最初创建后的值为nil,nil不等于@"") [yourTextField.text isEqualToString:@""] || yourTextField.text == nil //或者 yourTextField.text.length == 0
//其他方法一 //判断字符串是否为空 #define strIsEmpty(str) ([str isKindOfClass:[NSNull class]] || str == nil || [str length] < 1 ? YES : NO ) //方法二 - (BOOL) isBlankString:(NSString *)string { if (string == nil || string == NULL) { return YES; } if ([string isKindOfClass:[NSNull class]]) { return YES; } if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) { return YES; } return NO; }
通过枚举值调对应字符串
//定义枚举类型 typedef NS_ENUM(NSInteger, SubCityCategoryType){ SomeTypeKey = 0, }; //声明全局类型数组 extern SomeType const SomeTypes[]; //声明全局类型字符串函数 extern NSString * const SomeTypeIdentifier(SomeType Key); //定义类型数组 SubCityCategoryType const SubCityCategoryTypes[] = { SomeTypeKey }; //定义字符串函数 NSString * const SubCityCategoryTypeIdentifier(SomeType Key){ switch (Key) { case SomeTypeKey: return @"KeyString"; default: return @""; } } //传入枚举值通过字符串函数获取指定字符串 SubCityCategoryTypeIdentifier(SomeTypeKey) //使用方式
使用JSONKit将字符串,字典,数组转换成json格式
str = [string JSONString]; str = [dic JSONString]; str = [array JSONString];