一.NSString常见创建
1.声明一个常量字符串
1 NSString *str = @"abc";
2.通过构造方法创建字符串
1 NSString *str1 = [[NSString alloc]initWithString:@"abc"]; 2 NSString *str2 = [[NSString alloc]initWithUTF8String:"abc"]; 3 NSString *str3 = [[NSStringalloc]initWithFormat:@"%@%c",@"ab",'c'];
3.通过类方法创建字符串
1 NSString *str1 = [NSString stringWithString:@"abc"]; 2 NSString *str2 = [NSString stringWithUTF8String:"abc"]; 3 NSString *str3 = [NSString stringWithFormat:@"%@%c",@"ab",'c'];
二.字符串比较
1.判断两个字符串是否相等(isEqualToString)
1 NSString *str1 = @"1234567890"; 2 NSString *str2 = @"1234567890"; 3 BOOL ret = [str1 isEqualToString:str2]; 4 NSLog(@"ret is %d",ret);
输出结果:
2016-06-27 10:56:56.284 OcTest[561:282681] ret is 1 Program ended with exit code: 0
2.两个字符串比较函数(compare)
NSString *str1 = @"1234567890"; NSString *str2 = @"12345"; NSComparisonResult result = [str1 compare:str2]; if (result == NSOrderedAscending) { NSLog(@"str1 < str2"); } else if (result == NSOrderedDescending) { NSLog(@"str1 > str2"); } else if (result == NSOrderedSame) { NSLog(@"str1 = str2"); }
输出结果:
2016-06-27 11:03:48.707 OcTest[597:310397] str1 > str2 Program ended with exit code: 0
三.字符串截取
首先创建一个字符串,下面以str1为例:
1 NSString *str1 = @"1234567890";
1.截取到第六位(substringToIndex)
NSString *str = [str1 substringToIndex:6]; NSLog(@"str is %@",str);
输出结果:
2016-06-27 11:12:11.284 OcTest[637:341212] str is 123456 Program ended with exit code: 0
2.从第六位开始截取(substringFromIndex)
NSString *str = [str1 substringFromIndex:6]; NSLog(@"str is %@",str);
输出结果:
2016-06-27 11:15:12.630 OcTest[664:356189] str is 7890 Program ended with exit code: 0
3.字符串范围截取(substringWithRange)
NSString *str = [str1 substringWithRange:NSMakeRange(0, 5)]; NSLog(@"str is %@",str);
输出结果:
2016-06-27 11:17:38.833 OcTest[674:366407] str is 12345 Program ended with exit code: 0
四.一个字符串在另一个字符串中的位置(rangeOfString)
首先新创建一个字符串str2
NSString *str2 = @"1234";
NSRange range = [str1 rangeOfString:str2]; NSLog(@"range loc is %zd,range length is %zd",range.location,range.length);
输出结果:
2016-06-27 11:24:01.916 OcTest[684:394116] range loc is 0,range length is 4 Program ended with exit code: 0
五.字符串查询
NSString *str = @"f232423dsgerh23wd3349k00cv3"; NSScanner *scanner = [NSScanner scannerWithString:str]; while(![scanner isAtEnd] && ++scanner.scanLocation){ int result; if([scanner scanInt:&result]){ NSLog(@"%d",result); } }
输出结果:
2016-07-01 15:10:15.231 OCString[851:320391] 232423 2016-07-01 15:10:15.232 OCString[851:320391] 23 2016-07-01 15:10:15.232 OCString[851:320391] 3349 2016-07-01 15:10:15.232 OCString[851:320391] 0 2016-07-01 15:10:15.232 OCString[851:320391] 3 Program ended with exit code: 0
未来的你会感谢今天努力的自己
------Alen