文件操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
//【文件管理类 NSFileManager】
NSError * error = nil;//0
//ARC NSError __autorelease * error = nil;
//1.查看指定目录里面的文件(浅度遍历)
//第一个参数,要查看的文件夹路径
//第二个参数,错误信息
NSArray * fileContentsArray = [fm contentsOfDirectoryAtPath:PATH error:&error];
//操作文件,一定要有错误信息的判断,如果文件操作失败,没有做处理,后面的程序100%挂掉
if (error) {
//perror 打印错误信息
perror("contentsOfDirectoryAtPath");
}
//2.查看所有在这个文件夹下的文件(深度遍历)
//第一个参数,要查看的文件夹路径
//第二个参数,错误信息
NSArray * allFileContentsArray = [fm subpathsOfDirectoryAtPath:PATH error:&error];

//第一个参数:要创建文件夹的路径 这个路径是带有要创建的文件夹名的
//第二个参数:BOOL类型,控制,是否创建中间文件夹
//If YES, this method creates any non-existent parent directories as part of creating the directory in path. If NO, this method fails if any of the intermediate parent directories does not exist. This method also fails if any of the intermediate path elements corresponds to a file and not a directory.
//如果要创建的文件夹,含有中间路径,那么YES,表示如果没有这个中间路径,我们就连带中间路径一起创 建,如果存在,不用管它
//第三个参数:属性,创建文件夹的属性 默认属性nil
//第四个参数:错误信息
//返回值BOOL 判断创建是否成功
[fm createDirectoryAtPath:dstPath withIntermediateDirectories:YES attributes:nil error:&error];
//创建一个普通文件
//第一个参数:路径,这个路径是带有所要创建的文件名
//第二个参数:文件的内容,NSData 是OC当中二进制文件格式
//第三个参数:属性,默认nil
//利用他的返回值做出错判断
//NSString 转 NSData
NSString * str = @"今天赵雨铭同学,要给大家讲电子图书类!!!";
NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];
BOOL ret = [fm createFileAtPath:[PATH stringByAppendingPathComponent:@"1.txt"]contents:data attributes:nil];

//删除文件夹 和 普通文件 是一个方法
//删除是不可逆的~~~
//第一个参数:路径是带有要删除的文件信息的
//第二个参数:错误信息
[fm removeItemAtPath:PATH error:&error];

//copy文件
//第一个参数:要复制的原路径,带有文件名 或者 文件夹名
//第二个参数:目标路径 必须加上要复制过去的文件名,这个文件名可以重命名
//第三个参数:error信息
[fm copyItemAtPath:[PATH stringByAppendingPathComponent:@"MID/test"]toPath: [PATH stringByAppendingPathComponent:@"test"] error:&error];


//移动文件
//第一个参数:要移动源文件路径
//第二个参数:目标路径,也要带上文件名
//第三个参数:error
[fm moveItemAtPath:[PATH stringByAppendingPathComponent:@"1副本.txt"] toPath: [PATH stringByAppendingPathComponent:@"1.txt"] error:&error];

//判断文件是否存在
//返回值BOOL YES 表示该文件存在,NO 表示该文件不存在
BOOL ret = [fm fileExistsAtPath:[PATH stringByAppendingPathComponent:@"12.txt"]];
if (ret) {
NSLog(@"This file exist!");
} else {
NSLog(@"This file No exist!");
}

//判断这个文件是不是文件夹
//返回值BOOL YES 表示这个路径的文件存在 NO 不存在
//isDirectory 传入参数是一个BOOL * YES 表示是一个文件夹,如果NO 表示是一个普通文件
//- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory;
BOOL isDirectory = NO;
ret = [fm fileExistsAtPath:[PATH stringByAppendingPathComponent:@"MIDd"] isDirectory:&isDirectory];

if (ret) {
if (isDirectory) {
NSLog(@"This is a directory!");
} else {
NSLog(@"This is normal file!");
}
} else {
NSLog(@"No such file or directory!");
}

//获取文件的属性
NSDictionary * dic = [fm attributesOfItemAtPath:PATH error:&error];
NSLog(@"%@",dic);
// {
// NSFileCreationDate = "2015-12-30 01:40:30 +0000";
// NSFileExtensionHidden = 0;
// NSFileGroupOwnerAccountID = 20;
// NSFileGroupOwnerAccountName = staff;
// NSFileModificationDate = "2015-12-30 03:27:14 +0000";
// NSFileOwnerAccountID = 501;
// NSFileOwnerAccountName = LXL;
// NSFilePosixPermissions = 493;
// NSFileReferenceCount = 12;
// NSFileSize = 408;
// NSFileSystemFileNumber = 3450634;
// NSFileSystemNumber = 16777220;
// NSFileType = NSFileTypeDirectory;
// }


【文件句柄类 NSFileHandle
//创建一个读取文件的句柄
NSFileHandle * fhForRead = [NSFileHandle fileHandleForReadingAtPath:PATH];
//创建一个用于写入文件的句柄
NSFileHandle * fhForWrite = [NSFileHandle fileHandleForWritingAtPath:PATH];
//创建一个读写句柄
NSFileHandle * fhForUpdating = [NSFileHandle fileHandleForUpdatingAtPath:PATH];

//读取数据,读取的数据是一个二进制数据
//这个读取文件的方式是要把文件全部读取到内存中去
//在iOS程序中,都是采用这样的读取文件方式
NSData * data = [fhForRead readDataToEndOfFile]; //EOF
//读取指定长度的文件,字节数
[fhForUpdating readDataOfLength:9];

//写入数据是一个覆盖写
[fhForWrite writeData:dataForWrite];
//文件指示器到文件的末尾
[fhForWrite seekToEndOfFile];
//文件指示器,到文件的指定位置,这个位置是一个字节数
[fhForWrite seekToFileOffset:<#(unsigned long long)#>]
//把文件截短成100
[fhForUpdating truncateFileAtOffset:10];


//【plist文件】 Property List
//在plist文件当中,只能保存一下几种数据NSString NSDate NSData NSNumber NSArray NSDictionary
//plist是一个可视化轻量级文件,通常是保存一下数据量不是太大的文件,QQ登陆信息
//XML文本
//数据对象NSArray NSDictionary

//1.创建一个plist文件
//第一个参数:代表要创建plist的路径,包括plist文件名
//第二个参数:表示是否要原子操作
[dict1 writeToFile:[PATH stringByAppendingPathComponent:@"dict.plist"] atomically:NO];

[array writeToFile:[PATH stringByAppendingPathComponent:@"array.plist"] atomically:NO];


[file] - > [new] - >[file] - > [OS X] - > [Property List]

//2.读取plist
NSArray * plistArray = [[NSArray alloc] initWithContentsOfFile:PATH];
NSURL * url = [[NSURL alloc] initWithString:URL];
NSDictionary * dict = [[NSDictionary alloc] initWithContentsOfURL:url];

UILabel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.

//初始化window,并设置fram
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
//[UIScreen mainScreen].bounds] 获取当前屏幕的大小

//设置背景颜色
[self.window setBackgroundColor:[UIColor purpleColor]];

//Xcode 7.0 之后,必须有rootViewController
//Xcode 7.0 之前,可以不设置rootViewController
RootViewController * rootVC = [[RootViewController alloc]init];
self.window.rootViewController = rootVC;
//设置window为 keyWindow 并显示
[self.window makeKeyAndVisible];


return YES;
}
@implementation RootViewController
//视图已经加载
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//[self createUILabel];
//[self createNewLabel];
//UILabel * label =(UILabel *)[self.view viewWithTag:9];
// label.text = @"123";

}

-(void)createUILabel{

//红50绿100蓝30
//alpha 透明度,默认是1.0,取值范围0~1.0
//利用RGB生成一个颜色
//UIColor *color = [UIColor colorWithRed:50/255.0 green:100/255.0 blue:30/255.0 alpha:0.8];

//设置self.view的背景色
self.view.backgroundColor = [UIColor whiteColor];
//CGRect rect = CGRectMake(50, 50, 100, 100);

//初始化UILbel 并设置fram
//重新设置fram,会把之前设置的fram覆盖
UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];

//设置label的背景色
label.backgroundColor = [UIColor lightGrayColor];
label.text = @"NSLineBreakByTruncatingTail, NSLineBreakByTruncatingMiddleNSLineBreakByTruncatingTail,NSLineBreakByTruncating ,MiddleNSLineBreakByTruncatingTail.NSLineBreakByTruncatingMiddleNSLineBreakByTruncatingTail,NSLineBreakByTruncatingMiddle";

//设置字体的类型和大小
label.font = [UIFont systemFontOfSize:20];

//设置粗体
label.font = [UIFont boldSystemFontOfSize:20];

//设置斜体(不支持中文)
label.font = [UIFont italicSystemFontOfSize:20];

//获取所有字体
NSLog(@"%@",[UIFont familyNames]);

//设置字体,大小
label.font = [UIFont fontWithName:@"Thonburi" size:20];

//自适应宽度
//label.adjustsFontSizeToFitWidth = YES;
//内容对其方式
label.textAlignment = NSTextAlignmentLeft;

//label.textAlignment = NSTextAlignmentRight;
//label.textAlignment = NSTextAlignmentCenter;

//限制设置行数,如果文字不够,能显示多少行就显示多少行。
//如果行高不够,能显示多少行就显示多少行。
//默认值是0,表示行数最大
label.numberOfLines = 0;

label.lineBreakMode = NSLineBreakByTruncatingMiddle;
// NSLineBreakByWordWrapping = 0, 根据单词截断
// NSLineBreakByCharWrapping, 根据字符截断
// NSLineBreakByClipping, 简单截断
// NSLineBreakByTruncatingHead, 省略号在前
// NSLineBreakByTruncatingTail, 省略号在后
// NSLineBreakByTruncatingMiddle 省略号在中

label.shadowColor = [UIColor blueColor];
label.shadowOffset = CGSizeMake(3, 3);
//设置透明度
label.alpha = 0.8;
//标识
label.tag = 10;

[self.view addSubview:label];

}

算法题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
#include <stdio.h>
#include<string.h>
#include<ctype.h>
/*
1. 数字1、2、3、4,可以组成多个互不相同且无重复数字的三位数,请输出所有组合 (15分)
*/
void numOfDiffNumber()
{
int i , j , k;
for(i = 1; i <= 4 ;i ++){
for(j = 1;j <= 4; j++){
for(k = 1; k <= 4 ; k ++){
if (i != j && i != k && j != k){
printf("%d\n" , i * 100 + j * 10 + k);
}
}
}
}
}

/*
2.求 a + aa + aaa ... + aaaa...aaa(n个a)之和(15分)
其中a和n代表相关参数
如a = 2,n = 4表示求2 + 22 + 222 + 2222之和
*/
int sumOfNumber(int a, int n)
{
int num = 0;
int sum = 0;
int j = 0;
while(j <= n){
num = num * 10 + a;
sum += num;
j++;
}
return sum;
}

/*
2.传入数字n,求出1^1 + 2 ^ 2 + 3 ^ 3 + … + n ^ n的和(15分)

*/
long sumOfFactorial(long n)
{
long int i = 0, j = 0,sum = 0;
for(i = 1; i <= n; i++){
long int pruct = 1;
for(j = 1; j <= i; j++){
pruct *= i;
}
sum += pruct;
}
return sum;
}
/*1.判断是否是一个合法的手机号,是返回1,不是返回0 (15分)
要求:手机号以1开头总共有11位 并且手机号中不能有除了数字以外的其他字符
比如: 13812345678 是手机号
188a1234567 不是手机号
01381234567 不是手机号
188123456789 不是手机号
18912345 不是手机号
*/
int isPhoneNumberOfString(const char * phoneNumber)
{
int flag = 0;
int i = 0;
int l = strlen(phoneNumber);
if(phoneNumber[0] != '1' || l != 11)
{
flag = 0;
}
else
{
while(i < 11)
{
i = 1;
if(phoneNumber[i] >= '0' && phoneNumber[i] <= '9')
{
flag = 1;
}
else
{
flag = 0;
}
i++;
}
}
return flag;
}
/*
1.求整形数组中第二大元素的下标(15分)
n表示数组长度
如数组中元素为81 12 42 67 9 88,返回0
*/

int secondMaxIndex(int *arr, int n)
{
int i = 0, j = 0;
int c[n];
int temp = 0;
for(i = 0;i < n;i++){
c[i] = arr[i];
}

for(i = 0;i < n - 1; i++){
for(j = 0; j < n - 1 - i; j++){
if(c[j] < c[j + 1]){//升序 冒泡
temp = c[j];
c[j] = c[j + 1];
c[j + 1] = temp;
}
}
}

for(i = 0; i < n; i++){
if(c[1] == arr[i]){
return i;
}
}
return 0;
}


/*
2. 打印文件的扩展名(后缀) (15分)
比如 :
传入字符串 "/home/apple/oc.txt"
打印:txt
传入字符串 "/Users/apple/Desktop/ios.c"
打印:c
*/
const char *printExtensionOfFilePath(const char * path)
{
while(*path++ != '.');
const char *p = path;
return p;
}

/*
4.字符串后移指定位数,实现首尾循环(20分)
如传入"abcdefgh" 和3,则输出fghabcde
*/

void moveCharsToFront(char *c, int n)
{
int count = 1, i = 0, j = 0;
char a[256];
while(c[i] != '\0'){
a[i] = c[i];
i++;
count++;
}
for(i = 0; i < n; i++){
c[i] = c[count - n - 1 + i];
}
for(i = n; i < count - 1; i++){
c[i] = a[j];
j++;
}
printf("%s\n",c);

}
/*
//另一种方法
void moveCharsToFront(char *c, int n)
{
char a[100];
int i,j,x;
x=n-1;
for(i=0;c[i]!='\0';i++)
{
}
for(j=i-1;j>=0;j--)
{
if(j+n>i-1)
{
a[x]=c[j];
x--;
}
else{
c[j+n]=c[j];
}
}
for(j=0;j<n;j++)
{
c[j]=a[j];
}
printf("%s\n",c);
}
*/


/*
3. 输入一段字符串,已知字符串只由字母和空格构成,每两个单词间有一个或多个空格,统计其中的单词个数 (15分)
比如:传入 "welcome to qianfeng" 返回:3
*/
int countOfWordInString(const char * str)
{
int n = 1;
int i = 0;
//此处考虑字符串前有空格
// while(str[i] == ' ')
// i++;
//不考虑串前空格和串后空格
while(str[i++] != '\0')
{
if(str[i - 1] != ' ')
{
continue;
}
if(str[i - 1] == ' ' && str[i] != ' ' )
{
n++;
}
}
//此处考虑串后空格
// if(str[i - 2] == ' ')
// n--;
return n;
}

/*
3.已知英语单词可以使用空格、逗号、叹号、句号四个符号分割,统计一个英语字符串中单词的个数。(15分)
如 we are student,we are good student!
返回 7
*/
int numOfWordsInString(const char * str)
{
int i ,count = 0;
for(i = 0; str[i] != '\0';i++)
{
if(str[i] == ' ' || str[i] == ',' || str[i] == '!' ){
count++;
}
}
return count;
}

/*
4.返回字符串s2在字符串s1中出现的次数。(20分)
如s1为"drink your drink" s2为"drink"
返回值是2
*/
int numOfStr(const char * s1, const char * s2)
{
int count = 0;
int l1 = strlen(s1);
int l2 = strlen(s2);
for(int i = 0;i < l1; i++)
{
int n = 0;
for(int j = 0; j < l2; j++)
{
if(s1[i+j] == s2[j])
n++;
}
if(l2 == n)
count++;
}
return count;
}
/*
2.求字符串s2在字符串s1中出现的次数(20分)
比如:
输入:“abc123bc321bcde”, “bc”
输出:3
输入:“abc123bc321bcde”, “bcde”
输出:1
*/
int times(char *s1, char *s2)
{
int l2 = strlen(s2);
int i ,count = 0;
for (i = 0;s1[i] != '\0'; i++)
{
int n = 0;
for(int j = 0; j < l2 ; j++)
{
if (s1[i + j] == s2[j])
n++;
else
{
break;
}
}
if(l2 == n)
{
count++;
}
}
return count ;
}


/*
4.传入一段字符串,字符串中可能有任何字符,输出每种字符出现的次数,字符的顺序没有限制。(20分)
传入:"hello!!"
输出:
h:1
e:1
l:2
o:1
!:2
*/

void printNumOfChar(const char * str)
{
char c[256] = "";//存放字符
int num[256] = {0};//存放字符出现的次数
int i = 0;
while(*str != '\0'){
for(i = 0;c[i];i++){
if(c[i] == *str){
num[i]++;
break;
}
}
//如果字符不存在,添加到字符数组c中
if(c[i] == '\0'){
c[i] = *str;
num[i]++;
}
str++;
}
for(int i = 0;i <256; i++){
if(num[i] > 0){
printf("%c:%d\n",c[i],num[i]);
}
}
}

/*

void printNumOfChar(const char * str)
{
char a[256];
int i ,j ,x,n;
strcpy(a,str);

for(i=0;a[i]!='\0';i++){}
for(j=0;j<i;j++)
{
if(a[j]!='\0')
{
x=1;
for(n=j;n<i;n++)
{
if(j!= n && a[n] == a[j])
{
x++;
a[n]='\0';
}
}
printf("%c:%d\n",a[j],x);
}
}

}
*/


/*
1.统计字符串中的指定字符的个数 (20分)
传入:'a' "ajeiuaHAAaakdhsda"
结果:5
*/
int countOfChar(char c, char *str)
{
int i = 0;
int count = 1;
int l = strlen(str);//调用函数计算字符数组长度


for( i = 0; i < l ;i++){
if(c == str[i]){
count++;
}
}

return l;
}

/*
3.将字符串中出现的单词的首字母改为大写,其余字母小写,并输出(15分)
其中传入字符串中,字母既可以大写也可以小写
如传入"hEllO WOrld",输出"Hello World"
传入"wELCome TO heNan",输出"Welcome To Henan"
*/

void capitalWords(char *str)
{
int i = 0;
abc:
if(str[i] >= 'a' && str[i] <= 'z'){
str[i] = str[i] - 32;
}
for(i = i+1; str[i] != '\0'; i++){
if(str[i] == ' '){
i++;
goto abc;
}
if(str[i] >= 'A' && str[i] <= 'Z'){
str[i] = str[i] + 32;
}
}
printf("%s\n",str);

}


/*
5.字符串解压缩,并输出(20分)
src表示待解压的字符串
如传入a2bc3f4,解压为aabcccffff并输出
*/

void decompress(const char *src)
{

int i = 0,count = 1;
while(src[i] != '\0'){
i++;
count++;
}
char c[256];
int k = 0;
for(i = 0; i < count; i++){
if(src[i] >= 'a' && src[i] <= 'z'){
c[k++] = src[i];
}
if(src[i] >= '1' && src[i] <= '9'){
for(int j = 0; j < (src[i] - '1'); j++){
c[k++ ] = src[i-1];
}
}
}
printf("%s\n",c);

}

//字符串压缩
//如传入aabcccffff 压缩为a2bc3f4并输出
//source表示待压缩字符串, destion 用于存放压缩后的字符串
void compress(char *source, char *destion)
{
int count = 1;
int i;
for(i = 0; source[i] != '\0'; i++){
if(source[i] == source[i + 1]){
count++;
}else{
*destion = source[i];
destion++;
if(count != 1){
//考虑超过10的情况
int j = 0;
int num[4] = {0};
while(count > 0){
num[j] = count % 10;
count = count / 10;
j++;
}
j--;
while(j >= 0){
*destion++ = num[j] + '0';
j--;
}
//不考虑10以上的数字
*destion++ = count + '0';
count = 1;
}
}
}
}

/*
5.将字符中单词用空格隔开(20分)
已知传入的字符串中只有字母,各单词由全大写,全小写交替出现组成,试将每个单词隔开,
保留第一个单词首字母大写,其他单词全小写。
传入:"HELLOmyDEARworld"
打印:"Hello my dear world"

传入:"welcomeTObeijing"
打印:"Welcome to beijing"
*/

void separateString(const char * str)
{
int i = 0 ;
char c[256] = "";//保存修改后的字符串
int flag = 0;// 0 表示小写 1表示大写
if(isupper(str[0])){
flag = 1;
}
else{
flag = 0;
}
c[0] = toupper(str[0]); //处理首元素,转换成大写字母放入c中
int k=1;

while(str[i++] != '\0'){
int temp = 0; //临时标志位
if(isupper(str[i])){
temp = 1;
}
else{
temp = 0;
}
//和原来的标志位进行比较
if(flag == temp&&flag==0){ //相同 不拆分
c[k++] = str[i];
}else if(flag == temp)
{
c[k++] = tolower(str[i]);
}
else
{ //不同 表示大小写变了 既进入下一个单词
c[k++] = ' '; //先加空格
c[k++] = tolower(str[i]); //字母转换成小写
flag = temp; //记录新的字母状态
}

}
printf("%s\n",c);

}


/*
5.剔除字符串中的全部空格并打印(15分)
传入:" how are you? "
打印:howareyou?
*/
void stringWithoutSpaceInString(const char *str)
{ //此方法直接打印非空格字符
char c[256] = "";
int i, j = 0;
for(i = 0; str[i] != '\0'; i++)
{
if(str[i] != ' ')
{
c[j] = str[i];
j++;
}
}
printf("%s\n",c);
}

void withoutSpaceInString(char * str)
{ //此方法将将非空格字符赋值给另一个数组
int i = 0;
int j = 0;
char c[256] = "";
while(str[i] != '\0')
{
if(str[i] != ' ' )
c[j++] = str[i];
i++;
}
c[j++] = '\0';
strcpy(str, c);
printf("%s\n",str);
}

/*
2.定义一个函数把字符串中的大写转化为小写,把小写转化为大写,非字母不转化。(15分)
比如:Abc12aBC12转化成aBC12Abc12
说明:该题要求修改源字符串
*/
void converseString (char *str,int length)
{

int i;
for (i=0; i<length; i++)
{
if (str[i] >= 'a' && str[i] <= 'z')
{
str[i] = str[i] - 32;
}
else if (str[i] >= 'A' && str[i] <= 'Z')
{
str[i]= str[i] + 32;
}else
{
str[i] = str[i];
}
}
printf("%s\n",str);
}



/*
6.根据传入的字符串,打印N字图形。(15分)
如传入"helloworld"
打印

h h
ee e
l l l
l l l
o o o
w w w
o o o
r r r
l ll
d d

*/
void printString(const char * str)
{
int i ,j;
for(i = 0 ;str[i] != '\0';i++)
{
for(j = 0; str[j] !='\0'; j++)
{
if(i == j)
{
printf("%c",str[i]);
}
else if(j == 0 || str[j+1] =='\0')
{
printf("%c",str[i]);
}
else
{
printf(" ");
}
}
printf("\n");
}
}


/*
6.传入字符串,打印对应图形。(20分)
如传入 "helloworld"
传入的字符串长度是偶数
打印

h
e
l
l
o
w
o
r
l
d

*/
void printString(const char * str)
{
int l = strlen(str);
for(int i = 0; i < l / 2;i++)
{
for(int j = 0; j <= i; j++)
if(i == j)
{
printf("%c",str[i]);
}
else
{
do{
printf(" ");
}while(i == j);
}
printf("\n");
}

for(int m = 0; m < l / 2;m++)
{
for(int n = l / 2; n < l; n++)

if(m + n != (l - 1))
{
do{
printf(" ");
}while(m + n == (l -1));
}
else
{
printf("%c",str[l / 2 + m]);
}

printf("\n");

}

}

/*
6.传入一个字母,打印图形(20分)
如传入:’A’,打印:
A
BBB
CCCCC
DDDDDDD
EEEEEEEEE
FFFFFFFFFFF
GGGGGGGGGGGGG
*/

void printGraph(char c)
{
for (int i = 1; i <= 7; i++)
{
for (int j = 1;j <= 2 * i - 1; j++)
{
printf("%c",c + i - 1);
}
printf("\n");
}
}

/*输入G打印
A
BBB
CCCCC
DDDDDDD
EEEEEEEEE
FFFFFFFFFFF
GGGGGGGGGGGGG
*/

void print(char c)
{
int i, j;
for(i = 1 ;i <= c - 'A' + 1; i++){
for(j = 1; j <= 2 * i - 1; j++){
printf("%c",'A' + i - 1);
}
printf("\n");
}
}

/*
6.传入一个字母,打印图形(15分)
传入:'e'
打印
abcde
bcde
cde
de
e
ed
edc
edcb
edcba

*/

void printGraph(char c)
{
int n = c - 'a' + 1;
int i,j;
for(i = 1;i <= n;i++){
for(j = i;j < n + 1;j++){
printf("%c",'a' + j - 1 );
}
printf("\n");
}
for(i = 1;i < n;i++){
for(j =1 ;j <= i+1;j++){
printf("%c",c - j + 1 );
}
printf("\n");
}
}

UIImageView

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#import "RootViewController.h"

@interface RootViewController ()

@end

@implementation RootViewController

- (void)viewDidLoad {
[super viewDidLoad];

// [self createUIImageView];
[self UIImageViewAnimation];
}

-(void)UIImageViewAnimation{
UIImageView *bgView = [[UIImageView alloc]initWithFrame:self.view.bounds];
bgView.image = [UIImage imageNamed:@"back2.jpg"];
[self.view addSubview:bgView];

UIImageView *birdView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 121, 96)];
birdView.image = [UIImage imageNamed:@"DOVE 1"];

NSMutableArray *mArray = [NSMutableArray array];
for (int i = 1 ; i <19; i ++) {
NSString *PicName = [NSString stringWithFormat:@"DOVE %d",i];
UIImage *image = [UIImage imageNamed:PicName];
[mArray addObject:image];
}

birdView.animationImages = mArray;
birdView.animationDuration = 1;
birdView.animationRepeatCount = 2;
[birdView startAnimating];

[self.view addSubview:birdView];

}

//创建UIImageView
-(void)createUIImageView{
/*
UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"back2.jpg"]];
[self.view addSubview:imageView];
*/
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 200, 200)];
imageView.backgroundColor = [UIColor lightGrayColor];
imageView.image = [UIImage imageNamed:@"back2.jpg"];
imageView.contentMode = UIViewContentModeScaleAspectFill;
// UIViewContentModeScaleToFill
// UIViewContentModeScaleAspectFit
// UIViewContentModeScaleAspectFill
[self.view addSubview:imageView];



//UIImage在初始化图片时,能获得图片的size
UIImage *image = [UIImage imageNamed:@"back2.jpg"];
NSLog(@"%f----%f",image.size.width,image.size.height);
}

@end

UIAlertView

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79

#import "ViewController.h"

@interface ViewController ()<UIAlertViewDelegate>
{
int number;
}
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];


}
//点击屏幕就会触发此方法
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
number = arc4random()%2;
NSLog(@"number = %d",number);
if (number == 0) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"赶快还钱" delegate:self cancelButtonTitle:@"还钱" otherButtonTitles:@"不还",@"就不还", nil];
[alert show];
}
if (number == 1) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"还钱" delegate:self cancelButtonTitle:@"还钱" otherButtonTitles:@"不还",@"就不还", nil];


alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;

[alert show];

// UIAlertViewStyleDefault = 0,
// UIAlertViewStyleSecureTextInput,
// UIAlertViewStylePlainTextInput,
// UIAlertViewStyleLoginAndPasswordInput
}
}
#pragma mark -
#pragma mark delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (number == 0) {
switch (buttonIndex) {
case 0:
NSLog(@"%ld",buttonIndex);
break;
case 1:
NSLog(@"%ld",buttonIndex);
break;
case 2:
NSLog(@"%ld",buttonIndex);
break;

default:
break;
}

}else{

switch (buttonIndex) {
case 0:
NSLog(@"%ld",buttonIndex); NSLog(@"%@",[[alertView textFieldAtIndex:0]text]);
NSLog(@"%@",[[alertView textFieldAtIndex:1]text]);
break;
case 1:
NSLog(@"%ld",buttonIndex);
break;
case 2:
NSLog(@"%ld",buttonIndex);
break;

default:
break;
}
}


}
@end

路径解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

UIImage *image = [UIImage imageNamed:@""];
// 使用`imageNamed:`初始化的时候,会先检查缓存中是否存在要加载的照片,如不存在,图片首先会被缓存起来,然后才返回要加载的图片对象;如果存在,直接返回要加载的照片对象。

NSString *path = [[NSBundle mainBundle]pathForResource:@"1.png" ofType:nil];
NSLog(@"%@",path);
UIImage *image2 = [UIImage imageWithContentsOfFile:path];
// 使用`imageWithContentsOfFile:`创建图片的时候,是直接从磁盘上加载。当收到内存警告时,图片对象会被释放,下一次绘图的时候,需要重新加载。

NSData *data;
UIImage *image3 = [UIImage imageWithData:data];
// data 是照片数据,一般是请求返回的,然后通过`imageWithData:`创建图片。
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end

沙盒路径

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

// 数据是写在Library->Preferences下
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
NSLog(@"%p",defaults1);
NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults];
NSLog(@"%p",defaults2);

NSUserDefaults *defaults3 = [[NSUserDefaults alloc]init];
NSLog(@"%p",defaults3);

NSArray *tempArray = @[@"1",@"2"];
[defaults1 setObject:tempArray forKey:@"array"];

// 1、获取程序的Home目录
// NSString *homeDirectory = NSHomeDirectory();
// NSLog(@"path:%@", homeDirectory);

// 2、获取document目录
// NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentPath = [documentPaths objectAtIndex:0];
// NSLog(@"path:%@", documentPath);

// 3、获取Cache目录
// NSArray *CachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
// NSString *CachePath = [CachePaths objectAtIndex:0];
// NSLog(@"%@", CachePath);

// 4、获取Library目录
// NSArray *LibraryPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
// NSString *LibraryPath = [LibraryPaths objectAtIndex:0];
// NSLog(@"%@", LibraryPath);

// 5、获取Tmp目录
// NSString *tmpDir = NSTemporaryDirectory();
// NSLog(@"%@", tmpDir);

// 6、写入文件
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *docDir = [paths objectAtIndex:0];
// NSLog(@"%@",docDir);
// if (!docDir) {
// NSLog(@"Documents 目录未找到");
// }
// NSArray *contentArray = [[NSArray alloc] initWithObjects:@"内容",@"content",nil];
// NSString *filePath = [docDir stringByAppendingPathComponent:@"testFile.txt"];
// [contentArray writeToFile:filePath atomically:YES];


// 7、读取文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:@"testFile.txt"];
NSLog(@"%@",filePath);
NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath];
NSLog(@"%@", array);


// 8、判断一个文件是否存在,传入全路径(fileExistsAtPath)
// // 创建文件管理器
// NSFileManager * fileManager = [NSFileManager defaultManager];
//
// NSString * documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
// NSString * filePath = [documents stringByAppendingPathComponent:@"test"];
//
// // 判断一个文件是否存在,传入全路径
// if ([fileManager fileExistsAtPath:filePath]) {
// NSLog(@"it is exit");
// }


// 9、在Documents里创建目录
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentsDirectory = [paths objectAtIndex:0];
// NSLog(@"documentsDirectory%@",documentsDirectory);
// NSFileManager *fileManager = [NSFileManager defaultManager];
// NSString *testDirectory = [documentsDirectory stringByAppendingPathComponent:@"test"];
// // 创建目录
// [fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];


// 10、在目录下创建文件
// NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test00.txt"];
// NSString *testPath2 = [testDirectory stringByAppendingPathComponent:@"test22.txt"];
// NSString *testPath3 = [testDirectory stringByAppendingPathComponent:@"test33.txt"];
// NSString *string = @"写入内容,write String";
// [fileManager createFileAtPath:testPath contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
// [fileManager createFileAtPath:testPath2 contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
// [fileManager createFileAtPath:testPath3 contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];


// 11、获取目录列里所有文件名
// 两种方法获取:subpathsOfDirectoryAtPath 和subpathsAtPath
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentsDirectory = [paths objectAtIndex:0];
// NSLog(@"documentsDirectory%@",documentsDirectory);
// NSFileManager *fileManage = [NSFileManager defaultManager];
// NSString *myDirectory = [documentsDirectory stringByAppendingPathComponent:@"test"];
// NSArray *file = [fileManage subpathsOfDirectoryAtPath: myDirectory error:nil];
// NSLog(@"%@",file);
// NSArray *files = [fileManage subpathsAtPath: myDirectory ];
// NSLog(@"%@",files);


// 12、fileManager使用操作当前目录
// //创建文件管理器
// NSFileManager *fileManager = [NSFileManager defaultManager];
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentsDirectory = [paths objectAtIndex:0];
// //更改到待操作的目录下
// [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];
// //创建文件fileName文件名称,contents文件的内容,如果开始没有内容可以设置为nil,attributes文件的属性,初始为nil
// NSString * fileName = @"testFileNSFileManager.txt";
// NSArray *array = [[NSArray alloc] initWithObjects:@"hello world",@"hello world1", @"hello world2",nil];
// [fileManager createFileAtPath:fileName contents:array attributes:nil];

// 13、删除文件
// [fileManager removeItemAtPath:fileName error:nil];

}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

UIAlertController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

for (int i = 0 ; i < 2; i ++) {
UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(120 + i * 120, 120, 100, 50);
button.backgroundColor = [UIColor lightGrayColor];
if (i == 0) {
[button setTitle:@"alertView" forState:UIControlStateNormal];
}else{
[button setTitle:@"actionSheet" forState:UIControlStateNormal];
}
button.tag = 10 + i ;
[button addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:button];
}

}
-(void)onClick:(UIButton*)button{

if (button.tag == 10) {
NSLog(@"alertView");
[self alertView];
}else{
NSLog(@"actionSheet");
[self actionSheet];
}
}
-(void)actionSheet{
// 初始化UIAlertCOntroller
// Title:标题
// message:信息
// Style:样式
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"message" preferredStyle:UIAlertControllerStyleActionSheet];

// 初始化UIAlertAction
UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
NSLog(@"取消");
}];

UIAlertAction *firstBtn = [UIAlertAction actionWithTitle:@"first" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
NSLog(@"取消");
}];



[alertController addAction:cancelBtn];
[alertController addAction:firstBtn];
[self presentViewController:alertController animated:YES completion:nil];

}
-(void)alertView{
// 初始化UIAlertController
// Title:标题
// message:信息
// Style:样式
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"message" preferredStyle:UIAlertControllerStyleAlert];
// UIAlertControllerStyleActionSheet
// UIAlertControllerStyleAlert

// 初始化按钮
// Title:标题
// style:样式
// UIAlertController 上面只能有一个取消样式的按钮,否则会崩溃
UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
NSLog(@"取消");
}];
// UIAlertActionStyleDefault = 0,普通按钮
// UIAlertActionStyleCancel,取消按钮
// UIAlertActionStyleDestructive重置、销毁

// 添加文本输入框
[alertController addTextFieldWithConfigurationHandler:^(UITextField * textField) {
textField.placeholder = @"请输入";
}];

[alertController addTextFieldWithConfigurationHandler:^(UITextField * textField) {
textField.placeholder = @"第二个文本输入框";
}];

UIAlertAction *resetBtn = [UIAlertAction actionWithTitle:@"reset" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * action) {

UITextField *textField1 = alertController.textFields[0];
NSLog(@"%@",textField1.text);

UITextField *textField2 = alertController.textFields[1];
NSLog(@"%@",textField2.text);
}];


// 添加动作
[alertController addAction:cancelBtn];
[alertController addAction:resetBtn];


// 模态
[self presentViewController:alertController animated:YES completion:nil];
}
@end

UIActivityIndicatorView

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#import "myButton.h"

@implementation myButton

+(UIButton *)buttonWithFrame:(CGRect)frame BGColor:(UIColor *)color Title:(NSString *)title NormalImage:(UIImage *)normalImage Tag:(int)tag Method:(SEL)method Object:(id)object{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = frame;
button.backgroundColor = color;
[button setTitle:title forState:UIControlStateNormal];
button.tag = tag;
[button setBackgroundImage:normalImage forState:UIControlStateNormal];
[button addTarget:object action:method forControlEvents:UIControlEventTouchUpInside];
return button;
}

@end


#import "ViewController.h"
#import "myButton.h"
@interface ViewController ()
{
UIActivityIndicatorView *act;
}
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];


[self createBtn];
[self createActivityIndicatorView];
}
-(void)onClick:(UIButton*)button{
if (act.isAnimating == YES) {
[act stopAnimating];
}else if(act.isAnimating == NO){
[act startAnimating];
}

}
-(void)createActivityIndicatorView{

// UIActivityIndicatorViewStyleWhiteLarge,大白
// UIActivityIndicatorViewStyleWhite,白色
// UIActivityIndicatorViewStyleGray 灰色
// 初始化并设置样式
act = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
act.frame = CGRectMake(100, 300, 50, 50);
// 设置中心点为屏幕中心点
act.center = self.view.center;
[self.view addSubview:act];

act.backgroundColor = [UIColor redColor];

// 设置变大4倍
act.transform = CGAffineTransformMakeScale(4, 4);

act.tag = 10;
// 停止时是否隐藏,默认是YES
act.hidesWhenStopped = YES;
}
-(void)createBtn{
UIButton *startBtn = [myButton buttonWithFrame:CGRectMake(100, 100, 50, 50) BGColor:[UIColor lightGrayColor] Title:@"开始" NormalImage:nil Tag:10 Method:@selector(onClick:) Object:self];

[self.view addSubview:startBtn];

UIButton *endBtn = [myButton buttonWithFrame:CGRectMake(180, 100, 50, 50) BGColor:[UIColor lightGrayColor] Title:@"停止" NormalImage:nil Tag:11 Method:@selector(onClick:) Object:self];
[self.view addSubview:endBtn];

[self.view setBackgroundColor:[UIColor yellowColor]];
}
@end

路径解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#import "FyQuestion.h"

@implementation FyQuestion

// 判断是绝对路径: 以 /开头的就是绝对路径
// -->./ios/day1/
// -->/oc/day
- (BOOL)isAbsolutePath:(NSString *)path {
//直接利用判断开头的这样的方法 harPrefix
return [path hasPrefix:@"/"];
}

// 取得路径path最后的部分 /home/xuanmac ---> xuanmac, /home/xuanmac/1.txt--->1.txt
- (NSString *)lastPathComponent:(NSString *)path {
//第一步,判断是否末尾存在/
int flag = 0;
NSString * subStr = nil;
if ([path hasSuffix:@"/"]) {
//截取字符方法,subStringToIndex
subStr = [path substringToIndex:[path length] - 1];
flag = 1;
}

//利用查找字符串方法,option 是倒序查找
//查找方法,返回的是一个范围
NSRange range = {0,0};
if (flag) {
//NSBackwardsSearch 倒序查找的指令
range = [subStr rangeOfString:@"/" options:NSBackwardsSearch];
//substringFromIndex 从指定位置到字符串结尾,包括指定位置
return [subStr substringFromIndex:range.location + 1];
} else {
range = [path rangeOfString:@"/" options:NSBackwardsSearch];
return [path substringFromIndex:range.location + 1];
}
}

// 删除路径path最后的部分 /home/xuanmac/ ---> /home, /home/xuanmac/1.txt--->/home/xuanmac
- (NSString *)stringByDeletingLastPathComponent:(NSString *)path {

NSString * subStr = nil;
//判断path末尾是不是以/结尾
if ([path hasSuffix:@"/"]) {
subStr = [path substringToIndex:path.length - 1];
} else {
subStr = path;
}

//倒序查找
NSRange range = [subStr rangeOfString:@"/" options:NSBackwardsSearch];

NSString * str = [subStr substringToIndex:range.location];

return [NSString stringWithString:str];

}
// 在路径上追加路径/home/xuanmac/ 和 demo/abc-->/home/xuanmac/demo/abc
- (NSString *)stringByAppendingPathComponent:(NSString *)path withPath:(NSString *)subPath {
NSMutableString * mStr = [NSMutableString stringWithString:path];
//判断是否是以/结尾
if ([mStr hasSuffix:@"/"]) {
if ([subPath hasPrefix:@"/"]) {
[mStr appendString:[subPath substringFromIndex:1]];
} else {
[mStr appendString:subPath];
}

} else {
if ([subPath hasPrefix:@"/"]) {
[mStr appendFormat:@"/%@",[subPath substringFromIndex:1]];
} else {
[mStr appendFormat:@"/%@",subPath];
}
}

return [NSString stringWithString:mStr];
}

// 取得文件的扩展名/home/xuanmac/1.txt --> txt
- (NSString *)pathExtension:(NSString *)path {
#if 1
//pathExtension 获取路径拓展名
NSString * str = path.pathExtension;
return [NSString stringWithString:str];
#else
NSRange range = [path rangeOfString:@"." options:NSBackwardsSearch];
NSString * str = [path substringFromIndex:range.location + 1];
return [NSString stringWithString:str];
#endif
}

// 删除文件扩展名/home/xuanmac/1.txt --> /home/xuanmac/1
- (NSString *)stringByDeletingPathExtension:(NSString *)path {
NSRange range = [path rangeOfString:@"." options:NSBackwardsSearch];

NSString * str = [path substringToIndex:range.location];
return [NSString stringWithString:str];
}
// 去除里面多余的 /路径 Duplicate重复 Slash表示斜线
// path = @"///home//xuanmac/ios/oc/day1/"; 返回@"/home/xuanmac/ios/oc/day1"
- (NSString *) removeDuplicateSlash:(NSString *)path {
#if 1
//看到//我们就要处理掉一个,知道在path没有// NSNotFound
//path 转换成可变字符串
NSMutableString * mStr = [NSMutableString stringWithString:path];

while (1) {
NSRange range = [mStr rangeOfString:@"//"];
//判断是否还存在,如果不存在@"//",跳出循环
if (NSNotFound == range.location) {
break;
}
//每次都删除//当中的一个
[mStr deleteCharactersInRange:NSMakeRange(range.location, 1)];
}

//处理完//之后,我们要处理路径末尾的/
if([mStr hasSuffix:@"/"])
{
[mStr deleteCharactersInRange:NSMakeRange(mStr.length - 1, 1)];
}

return [NSString stringWithString:mStr];
#else
NSArray * array = [path componentsSeparatedByString:@"/"];
NSMutableArray * mArray = [NSMutableArray arrayWithArray:array];
[mArray removeObject:@""];

return [mArray componentsJoinedByString:@"/"];//?????
#endif
}
//-获取路径中的所有目录名---->/home/xuanmac/ios/oc --->home xuanmac ios oc
- (NSArray *)pathComponents:(NSString*)path {
return [path componentsSeparatedByString:@"/"];
}

+ (void)test {
FyQuestion * test = [[FyQuestion alloc] init];
NSLog(@"第一题");
NSLog(@"%hhd",[test isAbsolutePath:@"./ios/day1/"]);
NSLog(@"%hhd",[test isAbsolutePath:@"/ios/day1/"]);

NSLog(@"第二题");
NSString * str1 = [test lastPathComponent:@"/ios/day1/"];
NSLog(@"%@",str1);
NSString * str2 = [test lastPathComponent:@"/ios/day1/1.txt"];
NSLog(@"%@",str2);

NSLog(@"第三题");
NSString * str3 = [test stringByDeletingLastPathComponent:@"/ios/day1/"];
NSLog(@"%@",str3);
NSString * str4 = [test stringByDeletingLastPathComponent:@"/ios/day1/1.txt"];
NSLog(@"%@",str4);

NSLog(@"第四题");
NSString * str5 = [test stringByAppendingPathComponent:@"/ios/day1/" withPath:@"1.txt"];
NSLog(@"%@",str5);
NSString * str6 = [test stringByAppendingPathComponent:@"/ios/day1" withPath:@"/test/1.txt"];
NSLog(@"%@",str6);

NSLog(@"第五题");
NSLog(@"%@",[test pathExtension:@"/test/1.txt"]);

NSLog(@"第六题");
NSLog(@"%@",[test stringByDeletingPathExtension:@"/test/1.txt"]);
NSLog(@"第七题");
NSLog(@"%@",[test removeDuplicateSlash:@"/////////fdjkasj//fdhk///fdjsalfkjs///"]);
NSLog(@"第八题");

NSLog(@"第备用题");
}


@end