您的位置:首页 > 移动开发 > Objective-C

Object -C 数组 -- 笔记

2015-08-23 18:05 429 查看
//

// main.m

// Array

//

// Created by facial on 23/8/15.

// Copyright (c) 2015 facial_huo. All rights reserved.

//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {

@autoreleasepool {

// insert code here...

NSLog(@"Hello, World!");

//初始化一个不可变数组

NSArray *arry = [NSArray arrayWithObjects:@"one one", @"two", @"three", nil ];

NSLog(@"%@", arry);

//打印数组方法

//枚举器法

NSEnumerator * Enumes = [arry objectEnumerator];

id obj;

while (obj = [Enumes nextObject]) {

NSLog(@"%@", obj);

}

//快速枚举法

for(id obj in arry) {

NSLog(@"%@", obj);

}

//使用i值遍历

NSUInteger length = [arry count];

NSLog(@"%li", length);

for(int i = 0; i < length; i ++) {

NSLog(@"%@", [arry objectAtIndex: i]);

}

//不可变数组 NSMutableArray

//NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects: @"a", @"b", @"c", nil];

NSMutableArray *mutableArray = [NSMutableArray new];

// 增加元素

[mutableArray addObject: @"dog"];

[mutableArray addObject: @"cat"];

[mutableArray addObject: @"snake"];

NSLog(@"%@", mutableArray);

//删除元素, 如果有两个相同的元素, 这个操作会两个同时删除

[mutableArray removeObject: @"dog"];

//根据index去删除元素

[mutableArray removeObjectAtIndex: 1 ];

NSLog(@"%@", mutableArray);

//new mutable arry

NSMutableArray *colorArray = [NSMutableArray new];

[colorArray addObject:@"red"];

[colorArray addObject:@"yellow"];

[colorArray addObject:@"green"];

[colorArray addObject:@"black"];

//交换元素位置

// [colorArray exchangeObjectAtIndex:0 withObjectAtIndex:1 ];

//用枚举法的时候, 只能够在数组倒叙的情况下修改数组

NSEnumerator *enumeArray = [colorArray reverseObjectEnumerator];

NSString *str;

while (str = [enumeArray nextObject]) {

NSLog(@"%@", str);

}

// 字符串转化为数组

NSString *Str = @"Hi i am facial";

//把字符串变成数组, 使用componentsSeparatedByString

NSArray *testarry = [Str componentsSeparatedByString: @" "];

NSEnumerator * StrEnumer = [testarry reverseObjectEnumerator];

NSMutableArray * ReverseArray = [NSMutableArray new];

NSString *str_temp;

while (str_temp = [StrEnumer nextObject]) {

[ReverseArray addObject: str_temp];

}

//把数组变成字符串, 使用componentsJoinedByString

NSString *newStr = [ReverseArray componentsJoinedByString: @" "];

NSLog(@"%@", newStr);

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: