首先简单了解NSString的用法:
-定义字符串
//定义字符串1
NSString *str1 = @"good";
//NSString的定义方法
NSString *str2 = [[NSString alloc] init];
str2 = @"test";
NSString *str3 = [NSString string];
NSLog(@"str = %@,str2=%@,str3=%@",str1,str2,str3);
//initWithString的用法
NSString *str4 = [[NSString alloc] initWithString:@"pk"];
//stringWithString的用法
NSString *str5 = [NSString stringWithString:@"pk"];
NSLog(@"str4 = %@,str5=%@",str4,str5);
//initWithFormat的用法
NSString *str6 = [[NSString alloc]initWithFormat:@"%d_%@",1,str4];
NSLog(@"str6=%@",str6);
-比较字符串
//比较两个字符串是否相等:isEqualToString
//注意不能用'==',等是判断两个对象是否相等
if([str4 isEqualToString:str5]){
NSLog(@"两个字符串相等");
}else{
NSLog(@"两个字符串不想等");
}
NSLog(@"%p %p",str4,str5);
//判断两个对象是否相等
if(str4 == str5){
NSLog(@"指向同一个对象");
}
//[string componentsSeparatedByString:key]字符串按key分割,返回NSArray
NSArray *array = [str6 componentsSeparatedByString:@"_"];
NSLog(@"%@",array);
-查找字符串
//[string substringToIndex:i]字符串子串,到第i个
//[string substringFromIndex:i]从第i个开始
NSString *str6=@"abcdefg";
NSLog(@"substring to 2 :%@",[str6 substringToIndex:5]);//abcde
NSLog(@"substring to 2 :%@",[str6 substringFromIndex:5]);//efg
//按范围查找
NSRange rang;
rang.length = 4;
rang.location = 2;
NSLog(@"substring to 2 :%@",[str6 substringWithRange:rang]);
如:str6为abcdef 则得到cdef
NSString *str8=@"hello01.txt";
NSRange rang2 = [str8 rangeOfString:@"."];
if(rang2.location != NSNotFound){
NSLog(@"sub str location =%ld ,length=%ld",rang2.location,rang2.length);
}else{
NSLog(@"NSNotFound!!");
}