1 #import <Foundation/Foundation.h>
2
3 int main(int argc, const char * argv[]) {
4
5 NSMutableString *str1 = [NSMutableString stringWithFormat:@"age is %d", 10];
6
7 [str1 appendString:@" fuck me"]; // 会直接改变str1, 因为它可变字符串
8 NSLog(@"str1 = %@", str1);
9
10 NSRange range = [str1 rangeOfString:@"is"];
11
12 [str1 deleteCharactersInRange:range];
13
14 NSLog(@"str1 = %@", str1);
15
16 NSString *str2 = [NSString stringWithFormat:@"age is %d", 100];
17
18 // 这是创建新的字符串对象, 可以从其命名结构中看出, 这是便利构造器。
19 NSString *str3 = [str2 stringByAppendingString:@"11 13"];
20
21 NSLog(@"str1=%@, str2=%@", str1, str2);
22
23 return 0;
24 }
25 void stringWrite() {
26
27 [@"fuck\nme" writeToFile:@"/Users/sixleaves/Desktop/2.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
28
29 NSString *str = @"test test test";
30 NSURL *url = [NSURL fileURLWithPath:@"/Users/sixleaves/Desktop/2.txt"];
31
32 [str writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:nil];
33 }
34 void stringCreateAndRead() {
35 // 1.NSString 不可变的创建
36 NSString * str1 = @"swp";
37
38 // 一般不用这种写法, 太冗余
39 // NSString * str2 = [[NSString alloc] initWithString:@"fuck"];
40
41 NSLog(@"str1 = %@", str1);
42
43 // 2.格式化拼接字符串
44 NSString * str3 = [[NSString alloc] initWithFormat:@"age is =%d", 10];
45 NSLog(@"str3 = %@", str3);
46
47 // 3.C字符串转OC字符串
48 NSString * str4 = [[NSString alloc] initWithUTF8String:"swp love u"];
49 NSLog(@"str4 = %@", str4);
50
51 // 4.OC字符串转C字符串(OC中C字符串存得就是UTF8编码格式)
52 const char * str5 = [str4 UTF8String];
53 NSLog(@"str5 = %s", str5);
54
55 // 5.从文件或者URL中读取数据, 拼成字符串对象。
56 // 从文件
57 NSString * str6 = [[NSString alloc] initWithContentsOfFile:@"/Users/sixleaves/Desktop/1.txt" encoding:NSUTF8StringEncoding error:nil];
58 NSLog(@"\nstr6 = %@", str6);
59
60 // 从URL资源路径
61 // url参数是 协议:// + 路径
62 /*
63 ftp协议: ftp://
64 file协议: file://
65 http协议: http://
66 */
67 //NSURL *url = [[NSURL alloc] initWithString:@"file:///Users/sixleaves/Desktop/1.txt"];
68 NSURL *url = [NSURL fileURLWithPath:@"/Users/sixleaves/Desktop/1.txt"];
69
70 NSString *str7 = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
71 NSLog(@"\nstr7 = %@", str7);
72
73 NSURL * url2 = [[NSURL alloc] initWithString:@"http://www.baidu.com"];
74 NSString *str8 = [[NSString alloc] initWithContentsOfURL: url2 encoding:NSUTF8StringEncoding error:nil];
75 NSLog(@"str 8 = %@", str8);
76 /*
77 但是在编程中,我们更多的是利用便利构造器,从而屏蔽了alloc再initWithXXXX。
78 所以一般都会有一个类方法与对象方法相互对应。
79 [NSURL URLWithString:]
[NSString stringWithString]
80 [NSString stringWithFormat:];
81 [NSString stringWithContentsOfFile: encoding: error:];
82 [NSString stringWithContentsOfURL: enconding: error:];
83 */
84 }