OC NSString(字符串)
多行文字字面量
NSString * string = @"abC"
@"DEF"
@"hjk"
@"uuiop";
NSRange的使用
typedef struct _NSRange {
NSUInteger location;
NSUInteger length;
} NSRange;
//定义:
NSRange range = {2,2};
//使用:
NSString * newString = [string substringWithRange:range];
常用方法
在A字符串中查找B字符串,返回B字符串在A中的位置
- (NSRange)rangeOfString:(NSString *)searchString;
//举例:
NSRange range = [string rangeOfString:@"gs"];
if (range.length == 0) {
NSLog(@"没有找到liu");
}
if (range.location == NSNotFound) {
NSLog(@"没有找到liu");
}
NSCaseInsensitiveSearch 忽略大小写
[string rangeOfString:@"ha" options:NSCaseInsensitiveSearch]
不可变字符串常用方法
带占位符的拼接字符串方法 stringByAppendingFormat
NSString * newString = [string stringByAppendingFormat:@"def%d",12];
拼接字符串方法 stringByAppendingString
NSString * newString = [string stringByAppendingString:@"opiuuoo"];
填充字符串 stringByPaddingToLength: withString: startingAtIndex:
NSString * newstring = [string stringByPaddingToLength:10 withString:@"123" startingAtIndex:2];
分割字符串 componentsSeparatedByString
NSArray * array = [string componentsSeparatedByString:@"-"];
通过数组合并字符串 componentsJoinedByString
NSString * string = [array componentsJoinedByString:@"-"];
给字符串前后去空格 stringByTrimmingCharactersInSet
NSString * string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
替换字符串 stringByReplacingOccurrencesOfString
NSString * newString = [string stringByReplacingOccurrencesOfString:@"hu" withString:@" "];
根据range替换字符串 stringByReplacingCharactersInRange:
NSRange range = {4,4};
string = [string stringByReplacingCharactersInRange:range withString:@"shifan"];
大写字母转小写 lowercaseString
NSString * newString2 = [string2 lowercaseString];
小写字母转大写 uppercaseString
NSString * newString1 = [string1 uppercaseString];
首字母大写 capitalizedString
NSString * newString2 = [string2 capitalizedString];
字符串比较函数 compare:
NSComparisonResult rs = [string1 compare:string2];
忽略大小比较字符串 caseInsensitiveCompare:
NSComparisonResult rs = [string1 caseInsensitiveCompare:string2];
if (rs == NSOrderedAscending) {
NSLog(@"string1 < string2");
} else if (rs == NSOrderedSame) {
NSLog(@"string1 = string2");
} else {
NSLog(@"string1 > string2");
}
字符串转基本数据类型
int num = [string intValue];
double numd = [string doubleValue];
//还有: floatValue,integerValue,longLongValue,boolValue
可变字符串NSMutableString
初始化方法
NSMutableString * string = [[NSMutableString alloc] initWithCapacity:5];
NSMutableString * s = [[NSMutableString alloc] initWithString:@"ab"];
追加方法
[s appendFormat:@"%d",1];
[s appendString:@"123"];
插入方法
[string insertString:@"90" atIndex:2];
替换方法
[string replaceCharactersInRange:range withString:@"jj"];
删除方法
[string deleteCharactersInRange:range];
不可变字符串转可变字符串(重置字符串)
[string setString:str];