[OC Foundation框架 - 5] NSString的常用方法
1 NSString *s1 = @"0123456789";
1.比较
使用 == 号比较的是字符串地址
1 NSString *s4 = @"abcdefg"; 2 NSString *s4_sub = [s4 substringToIndex:3]; 3 NSLog(@"subStr:%@, %d", s4_sub, @"abc" == s4_sub); // abc, 0 4 NSLog(@"subStr:%@, %d", s4_sub, [@"abc"isEqualToString:s4_sub]); // abc, 1
2.查找
1 NSLog(@"The character at index 2 --> %c",[s1 characterAtIndex:2]); // 2 2 NSRange range = [s1 rangeOfString:@"234"]; 3 if (range.location != NSNotFound) { 4 NSLog(@"%@", NSStringFromRange([s1 rangeOfString:@"234"])); // {2, 3} 5 }
3.串接
1 NSString *s3 = [NSStringstringWithFormat:@"%@%@", s1, s2]; 2 NSLog(@"%@", [@"www."stringByAppendingString:@"baidu.com"]); // www.baidu.com
4.分解
1 (1)- (NSArray) componentsSeparatedByString:(NSString *)
5.大小写转换
1 NSLog(@"%@", [@"aBc"uppercaseString]); // ABC 2 NSLog(@"%@", [@"AbC"lowercaseString]); // abc
6.路径操作:串联、分解...
7.扩展名
1 NSLog(@"extension : %@", [@“test.txt" pathExtension]); // txt
8.字符数
1 NSLog(@"%ld", [@"0123456789"length]); // 10
9.子串
1 NSLog(@"%@", [s1 substringWithRange:NSMakeRange(2, 3)]); // 包含index, 234 2 NSLog(@"%@", [s1 substringFromIndex:2]); // 包含index, 23456789 3 NSLog(@"%@", [s1 substringToIndex:2]); // 不包含index, 01
10.判断字符串是否为空
1 if (s1 == nil || s1.length == 0) { 2 NSLog(@"字符串为空"); 3 }
11.prefix & suffix
1 NSLog(@"%d", [@"0123456789"hasPrefix:@"012"]); // 1 2 NSLog(@"%d", [@"0123456789"hasSuffix:@"789"]); // 1
12.字符串与基本数据类型的转换
1 // 基本数据类型 int float double char 2 3 // 1.int类型转换成字符串 4 int a = 10; 5 NSString *s1 = [NSStringstringWithFormat:@"%d", a]; 6 NSLog(@"s1 is %@", s1); 7 8 // 2.float -> NSString 9 float f = 3.1415f; 10 NSString *s2 = [NSStringstringWithFormat:@"%.4f", f]; 11 NSLog(@"s2 is %@", s2); 12 13 // 3.double -> NSString 14 double d = 3.1415; 15 NSString *s3 = [NSStringstringWithFormat:@"%.4f", d]; 16 NSLog(@"s3 is %@", s3); 17 18 // 4.char -> NSString 19 char c = 'A'; 20 NSString *s4 = [NSStringstringWithFormat:@"%c", c]; 21 NSLog(@"s4 is %@", s4); 22 23 // 5.NSString -> int 24 NSString *s5 = @"433"; 25 int a2 = [s5 integerValue]; 26 NSLog(@"a2 = %d", a2); 27 28 // 6.NSString -> float 29 NSString *s6 = @"3.1415"; 30 float f2 = [s6 floatValue]; 31 NSLog(@"f2 = %.4f", f2); 32 33 // 7.NSString -> double 34 NSString *s7 = @"3.1415"; 35 double d2 = [s7 doubleValue]; 36 NSLog(@"d2 = %.4f", d2); 37 38 //注意, 传入的字符串必须是符合格式要求的, 才能返回正确结果 39 NSLog(@"i123 double format = %f", [@"i123"doubleValue]); // 0.000000 40 41 // 8.NSString -> char 42 NSString *s8 = @"a"; 43 char c2 = [s8 characterAtIndex:0]; 44 NSLog(@"c2 = %c", c2);