1.截取字符串
NSString *string = @"ABCDEFG";
//截取下标 [0,3) 。即下标3之前的字符串,不包含第3位
NSString *str1 = [string substringToIndex:3];
输出结果为:ABC
//截取下标[2,length-1]。即下标2之后的字符串,包含第2位
NSString *str2 = [string substringFromIndex:2];
输出结果为:CDEFG
//从第3位开始截取一个长度为4的字符串
NSString *str3 = [string substringWithRange:NSMakeRange(3,4)];
输出结果为:DEFG
//定位字符串
NSRange range = [string rangeOfString: @"ABCD"];
输出结果 range.location=0 ; range.length = 4 ;
2.字符串大小写转换
//全部字符 小写转大写
-(NSString *)uppercaseString;
//全部字符 大写转小写
-(NSString *)lowercaseString;
//字符串首字母变大写,其他字母都变小写
-(NSString *)capitalizedString;
3.分割字符串
NSString *string =@"CBA?NBA";
NSArray *array = [string componentsSeparatedByString:@"?"]; //从字符?中分隔成2个元素的数组
NSLog(@"array:%@",array); //结果是CBA和NBA
4.字符串转化为数字型再计算
NSString *string =@"100.00";
int a = [string intValue];
NSInteger b = [string integerValue];
CGFloat c = [string floatValue];
double d = [string doubleValue];
5.字符串比较
NSString *str1 = @"lion";
NSString *str2 = [NSString stringWithFormat:@"lion"];
if ([str1 isEqualToString:str2]) {
NSLog(@"字符串内容一样");
}
if (str1 == str2) {
NSLog(@"字符串地址一样");
}
//这个方法可以用来比较两个字符串内容的大小
- (NSComparisonResult)compare:(NSString *)string;
NSComparisonResult是一个枚举,有3个值:
如果左侧 > 右侧,返回NSOrderedDescending,
如果左侧 < 右侧,返回NSOrderedAscending,
如果左侧 == 右侧返回NSOrderedSame
6.字符串拼接
NSString *str =@"www";
NSString * str1 = [str stringByAppendingString:@".jianshu.com"];
NSString * str2 = [NSString stringWithFormat:@"%@%@", str,@".jianshu.com"];
7.插入字符串、替换字符串、删除字符串
NSString *str =@"www.baidu G.com";
NSString * str1 = [str stringByReplacingOccurrencesOfString:@"baidu" withString:@"jianshu"];//替换 输出结果:www.jianshu G.com
NSString * str2 = [str stringByReplacingOccurrencesOfString:@"baidu G" withString:@""];//删除 输出结果:www..com
NSString * str3 = [str stringByReplacingOccurrencesOfString:@" " withString:@""];//删除空格号 输出结果:www.baiduG.com
NSString *str =@"abcd";
NSRange range1 = {2,0};
NSRange range2 = {2,2};
NSString * str1 = [str stringByReplacingCharactersInRange:range1 withString:@"GG"];//插入 输出结果:abGGcd
NSString * str2 = [str stringByReplacingCharactersInRange:range2 withString:@"GG"];//替换 输出结果:abGG
NSMutableString *str=[[NSMutableString alloc]initWithString:@"abcd"];//存在堆区,可变字符串
[str insertString:@"G" atIndex:1];//插入 输出结果:aGbcd
NSRange range = {1,2};
[str deleteCharactersInRange:range];//删除 输出结果:ad
NSMutableString *str=[[NSMutableString alloc]initWithString:@"abcd"];
NSRange range1 = {1,0};
NSRange range2 = {1,3};
[str replaceCharactersInRange:range1 withString:@"GG"];//插入 str输出结果:aGGbcd
[str replaceCharactersInRange:range2 withString:@"GG"];//替换 str输出结果:aGG
8.带引号的字符串
NSString *string = @"hello, \"world\"";
NSLog(@"带引号的字符串:%@",string);
NSString *string2 = [NSString stringWithFormat:@"hello,\"%@\"",@"世界"];
NSLog(@"拼接字符串:%@",string2);
网友评论