NSString是objective-c的字符串,这里总结下NSString的常用方法。
//1. 串初始化
NSString *str1 = [NSString stringWithString:@"test"];
NSLog(@"str1 is %@",str1);
//2.快速创建一个字符串
NSString *str2 = [[NSString alloc]initWithString:str1];
NSLog(@"str2 is %@",str2);
NSString *str3 = [NSString stringWithString:str1];
NSLog(@"str3 is %@",str3);
//3.获取串长度
int l = [str1 length];
NSLog([NSString stringWithFormat:@"length = %d", l]);
//4.创建一个格式化字符串
NSString *str4 = [[NSString alloc]initWithFormat:@"%d",10];
NSString *str5 = [NSString stringWithFormat:@"%.2f",10.8099887];
NSLog(@"str4 = %@",str4);
NSLog(@"str5 = %@",str5);
//5.比较两个字符串内容是否相等
if ([str2 isEqualToString:str3]) {
NSLog(@"str6 is EqualToString str7");
}else{
NSLog(@"str6 is not EqualToString str7");
}
//6.转换为基本数据类型
NSString *str6 = @"3";
float f1 = [str8 floatValue];
NSLog(@"str6 = %.2f",f1);
//7.字符串拆分为数组
NSString *str7 = @"命 运 就 算 颠 沛 流 离";
NSArray *array = [str9 componentsSeparatedByString:@" "];
NSLog(@"array = %@",array);
NSLog(@"array[0] = %@",array[0]);
//8.拼接
NSString *str8 = [s stringByAppendingString:@" and test again"];
NSLog(@"string after append is %@",str8);
//9.获取子串
NSRange rng = NSMakeRange(5, 4);
NSString *ssub = [str8 substringWithRange:rng];
NSLog(@"sub string is %@", ssub);
//10.从文件中获取字符串
NSString *sFromFile = [[NSString alloc] initWithContentsOfFile:@"Info.plist"];
NSLog(@"file string is %@", sFromFile);
//11.从网页上获取字符串
NSURL *url = [[NSURL alloc] initWithString:@"http://www.macfans.com.cn/"];
NSString *sFromUrl = [[NSString alloc] initWithContentsOfURL:url];
NSLog(@"URL string is %@", sFromUrl);
//12.查询子串
NSString *ssearch = @"girl";
NSString *sfrom = @"find a perfect girl in the world. -- paul liu";
rng = [sfrom rangeOfString:ssearch];
NSLog(@"find a girl in %d,%d", rng.location, rng.length);