OC语言基础之NSString
1.字符串的创建
1: NSString *s1 = @"jack";
2:
3: //NSString *s2 = [[NSString alloc] initWithString:@"jack"];
4:
5: NSString *s3 = [[NSString alloc] initWithFormat:@"age is %d", 10];
6:
7: // C字符串 --> OC字符串
8: NSString *s4 = [[NSString alloc] initWithUTF8String:"jack"];
9: // OC字符串 --> C字符串
10: const char *cs = [s4 UTF8String];
11:
12: // NSUTF8StringEncoding 用到中文就可以用这种编码
13: NSString *s5 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/1.txt" encoding:NSUTF8StringEncoding error:nil];
14:
1: /*
2: 一般都会有一个类方法跟对象方法配对
3: [NSURL URLWithString:<#(NSString *)#>];
4: [NSString stringWithFormat:@""];
5: [NSString stringWithContentsOfFile:<#(NSString *)#> encoding:<#(NSStringEncoding)#> error:<#(NSError *__autoreleasing *)#>];
6:
7: */
2.常用方法
1)检查前缀
1: NSString *str = @"qq=12344&pwd=adadfs";
2: [str hasPrefix:@"qq="];
3:
4: [str hasSuffix:@"fs"];
2)大小写转换
1: NSString *str = [@"adbDAd" lowercaseString];
2: NSString *upStr = [str uppercaseString];
3: NSLog(@"%@", upStr);
4: // [[@"adbDAd" lowercaseString] isEqualToString:@"adsfasd"];
3)可变字符串
1: NSMutableString *str = [[NSMutableString alloc] initWithCapacity:0];
2:
3: [str appendFormat:@"123"]; //123
4: // NSLog(@"%@", str);
5: //
6: // NSString *str1 = @"123";
7: // NSString *str2 = [str1 stringByAppendingString:@"aaaa"];
8: // NSLog(@"%@", str2);
9: //
10: NSRange rang3 = [str rangeOfString:@"3"];
11: [str deleteCharactersInRange:rang3];
12: NSLog(@"%@", str);
13:
14: [str insertString:@"aaa" atIndex:0];
15:
16: // @"3" @""
17: [str replaceOccurrencesOfString:@"3"
18: withString:@""
19: options:NSLiteralSearch
20: range:NSMakeRange(0, str.length)];
21: NSLog(@"%@", str);