本文原创
总结一下NSString的那些常用的方法和技巧
1.截取字符串
//从索引值为1的位置开始截取字串 (包含1的位置),一只截取到最后
NSString *substring = [@"abcdefg" substringFromIndex:1];
NSLog(@"%@",substring);//打印结果:bcdefg
//从字符串开始 截取到索引值处(不包含索引值位置)
NSString *substring1 = [@"abcdefg" substringToIndex:1];
NSLog(@"%@",substring1);//打印结果:a
//截取某一段自子串(range代表一个范围 location代表截取的开始位置 length代表截取长度)
NSString *substring2 = [@"abcdefg" substringWithRange:NSMakeRange(1, 3)];
NSLog(@"%@",substring2);//打印结果:bcd
2.字符串拼接
//字符串拼接
//在原有的字符串后面追加一个字符串
NSString *appendstring = [@"abc" stringByAppendingString:@"def"];
NSLog(@"%@",appendstring);//打印结果:abcdef
//在原有的字符串后面追加一个格式化字符串(格式化字符串的意思是:将某种格式的字符串转化为另外一种格式。如String型转为int型)
NSString *appendstring1 = [@"abc" stringByAppendingFormat:@"%d",123];
NSLog(@"%@",appendstring1);//打印结果:abc123
3.字符串的替换
可以替换一些敏感词或者把带有空格的字符串去掉空格
NSString *contentString = @"hi dsbdsb";
//把敏感词dsb替换成***
NSString *replaceString = [contentString stringByReplacingOccurrencesOfString:@"dsb" withString:@"***"];
NSLog(@"%@",replaceString);
//打印结果:hi ******
4.字母大小写的转换
NSString *uppercaseString = [@"abc" uppercaseString];
NSLog(@"转大写字母%@",uppercaseString);//打印结果:大写字母ABC
NSString *lowercaseString = [uppercaseString lowercaseString];
NSLog(@"转小写字母%@",lowercaseString);//打印结果:小写字母abc
NSString *capitalizedString = [@"i love you" capitalizedString ];
NSLog(@"首字母大写%@",capitalizedString);//打印结果:首字母大写I Love You
5.字符串追加
//NSMutableString可变字符串
NSMutableString *str4 = [[NSMutableString alloc]initWithString:@"abcdefg"];
NSMutableString *str5 = [NSMutableString stringWithString:@"abcdefg"];
//在原字符串上直接追加字符串
[str4 appendString:@"hjk"];
NSLog(@"%@",str4);//打印结果:abcdefghjk
//在原字符串上直接追加格式化字符串
[str5 appendFormat:@"%d",133];
NSLog(@"%@",str5);//打印结果:abcdefg133
6.字符串插入
NSMutableString *str5 = [NSMutableString stringWithString:@"abcdefg"];
//将一个字符串插入到一个索引位置处,拼接字符串
[str5 insertString:@"nini" atIndex:2];
NSLog(@"插入字符串:%@",str5);//打印结果:插入字符串:abninicdefg
//删除某一范围字符串
[str5 deleteCharactersInRange:NSMakeRange(2 , 3)];
NSLog(@"%@",str5);//打印结果:abicdefg
7.NSNumber与基本数据类型互转
//Float型储存NSNumber类型的对象
NSNumber *floatOfNumber = [NSNumber numberWithFloat:3.14159];
//NSNumber类型的对象转回为基本数据类型。
floatOfNumber floatValue];
NSLog(@"%@",floatOfNumber);
其他类型转换如下: