OC中对字符串进行操作使用了Foundation框架中的NSString类(不可变)、NSMutableString类(可变)。
NSString
1、创建字符串
[objc] view plaincopy
NSString *str1 = @"我在学习OC";
NSString *str2 = [[NSString alloc] initWithString: @"我在学习OC"];
NSString *str3 = [NSString stringWithFormat: @"我在学习%@",@"OC"];
NSString *str4 = [[NSString alloc] initWithUTF8String:"我在学习OC"]; // 由C字符串转换成OC字符串
2、获取字符串长度
[objc] view plaincopy
NSUInteger length = str.length;
3、获取字符串某个位置的字符
[objc] view plaincopy
unichar c = [str characterAtIndex:1]; // 索引从0开始
4、截取字符串
[objc] view plaincopy
NSRang *rang = {1,2}; //location(索引开始的位置)、length(截取的长度);
NSString *subString = [str substringWithRange:rang];
5、获取子字符串在字符串中的索引位置和长度
[objc] view plaincopy
NSRange range = [str rangeOfString:subString]; // 如果未找到 返回{-1, 0}
6、判断字符串内容是否相同
[objc] view plaincopy
BOOL isEqual = [str1 isEqualToString:str2]
7、替换字符串中的子字符串为给定的字符串
[objc] view plaincopy
NSString * newStr = [str stringByReplacingOccurrencesOfString: @"a" withString: @"b"];
NSMutableableString
1、追加字符串返回新字符串
[objc] view plaincopy
NSString *str = it
NSString *newStr = [str stringByAppendingString: @“heima”];
2、追加字符串
[objc] view plaincopy
NSMutableableString *mstr = [[NSMutableableString alloc] init];
[mstr appendString: @“黑马”];
3、在指定的索引位置插入字符串
[objc] view plaincopy
[mstr insertString: @“itheima” atIndex:2];
4、删除指定范围的字符串
[objc] view plaincopy
NSRange range = {3,5};
[mstr deleteCharactersInRange:rang];
|
|