- 创建不可变数组NSArray
1 //创建数组的时候数组成员放在中括号中,NSLog打印时,数组是被放在小括号中 2 NSArray *array = @[@"bei", @"jing", @"huan", @"ying", @"nin"]; 3 4 #if 0 5 #pragma mark 对象方法创建数组 6 NSArray *array1 = [[NSArray alloc] initWithArray:array1]; 7 NSArray *array2 = [[NSArray alloc] initWithObjects:@"bei", @"jing", @"huan", @"ying", @"nin", nil]; 8 #endif 9 10 #pragma mark 类方法创建数组 11 NSArray *array1 = [NSArray arrayWithArray:array]; 12 NSArray *array2 = [NSArray arrayWithObjects:@"bei", @"jing", @"huan", @"ying", @"nin", nil];
- 数组成员的个数
1 //实例化一个数组对象 2 NSArray *array = @[@"bei", @"jing", @"huan", @"ying", @"nin"]; 3 //@property (readonly) NSUInteger count; 4 //作用:获取数组中的成员个数 5 NSLog(@"%lu",[array count]);
- 取出数组中的成员
1 //实例化一个数组对象 2 NSArray *array = @[@"bei", @"jing", @"huan", @"ying", @"nin"]; 3 //- (id)objectAtIndex:(NSUInteger)index; 4 //作用:根据下标获取数组中对应的元素 5 NSLog(@"%@", [array objectAtIndex:0]);
- 根据元素的值获取对应的下标
1 NSArray *array = @[@"bei", @"jing", @"huan", @"ying", @"nin"]; 2 //- (NSUInteger)indexOfObject:(id)anObject; 3 //作用:根据元素的值找第一个对应的下标 4 NSLog(@"%lu", [array indexOfObject:@"huan"]);
- 字符串的分割和数组元素的拼接
1 NSString *string1 = @"chen$chao$ni$hao$ma"; 2 //- (NSArray *)componentsSeparatedByString:(NSString *)separator; 3 //作用:将字符串按照某个字符串进行分割,分割后的字符串保存在一个数组中作为数组的元素 4 NSArray *arrayFromString1 = [string1 componentsSeparatedByString:@"$"]; 5 6 //- (NSString *)componentsJoinedByString:(NSString *)separator; 7 //作用:将数组中的元素按照某个字符串拼接成一个字符串 8 NSString *stringFromArray1 = [arrayFromString1 componentsJoinedByString:@" "]; 9 NSLog(@"%@", stringFromArray1); 10 11 //- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator NS_AVAILABLE(10_5, 2_0); 12 //作用:按照字符集进行切割 13 NSString *string2 = @"chen$chao#[email protected]&ma"; 14 NSArray *arrayFromString2 = [string2 componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"$#@&"]]; 15 NSString *stringFromArray2 = [arrayFromString2 componentsJoinedByString:@" "]; 16 NSLog(@"%@", stringFromArray2);
时间: 2024-10-08 09:55:10