1 #import <Foundation/Foundation.h> 2 3 int main(int argc, const char * argv[]) { 4 @autoreleasepool { 5 //判断字符串前缀 6 NSString *str1=@"iOS-study"; 7 BOOL result1=[str1 hasPrefix:@"iOS"]; 8 //判断字符串后缀 9 NSString *str2=@"study.jpg"; 10 BOOL result2=[str2 hasSuffix:@".jpg"]; 11 //分割字符串 12 NSString *str3=@"i am a new programmer"; 13 NSArray *array=[str3 componentsSeparatedByString:@" "]; //根据给定字符分割 14 NSLog(@"%@",array); //直接打印数组(一般不允许用在正式程序中) 15 //截取字符串 16 NSString *str4=[str3 substringToIndex:4]; //从字符串开始截取到第4位之前 17 NSString *str5=[str3 substringFromIndex:4]; //从第4位开始截取到字符串末位 18 //根据位置和截取长度截取字符串 19 NSRange rang1; 20 rang1.location=7; 21 rang1.length=3; 22 NSString *str6=[str3 substringWithRange:rang1]; //根据rang截取第7位开始的3个字符 23 NSRange rang2=[str3 rangeOfString:@"programmer"]; //获得字符串的起始位置和长度 24 //拼接字符串 25 NSString *str7=@"Good",*str8=@"bye"; 26 NSString *str9=[[NSString alloc]initWithFormat:@"%@%@",str7,str8]; //实例初始化法拼接 27 NSString *str10=[str7 stringByAppendingString:str8]; //直接拼接 28 NSString *str11=[str7 stringByAppendingFormat:@"-%@",str8]; //拼接中加入其他字符 29 //查询字符串 30 NSRange rang3=[str3 rangeOfString:@"new"]; //查询字符串的位置 31 NSLog(@"%@",NSStringFromRange(rang3)); //显示字符串所在位置 32 if(rang3.location==NSNotFound){ 33 NSLog(@"Can‘t find"); 34 } 35 else{ 36 NSLog(@"location=%ld,length=%ld",rang3.location,rang3.length); 37 } 38 } 39 return 0; 40 }
NSString基础2-判断前缀、后缀、分割、截取、拼接、查询
原文:http://www.cnblogs.com/wangyang1987/p/5106793.html