Objective-C之数组

 

数组遍历的两种方式

 

 

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
//也可以用:NSArray *array = [NSArray arrayWithObjects:@"One",@"Two",@"Three",nil];
	NSArray* array = [[NSArray alloc] initWithObjects:
					  @"One",@"Two",@"Three",nil];  //nil起结束标志的作用
	
	NSLog(@"%lu", [array count]);
	
	//第一种遍历方法:
	for(int i = 0; i < array.count; i++)
	{   //如果知道数组里存的对象如本题则可以用NSString接收,如果不知道则可以用id接收
		//id obj = [array objectAtIndex:i];
		NSString* str = [array objectAtIndex:i];
		NSLog(@"%@", str);
	}
	
	//第二种变量方法:快速枚举
	for(NSString* obj in array)
	{
		NSLog(@"%@", obj);
	}
	
	NSArray* array2 = [NSArray arrayWithArray:array];
	
	
    [pool drain];
    return 0;
}

 字符串分割成数组对象与连接

 

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
    NSString* str = @"one,two,three,four,five";
	//分割字符创为数组,下例以“,”分割
	NSArray* array = [str componentsSeparatedByString:@","];
	for(NSString* obj in array)
	{
		NSLog(@"%@", obj);
	}
	
	//链接字符串,下例以空格连接
	str = [array componentsJoinedByString:@" "];
	NSLog(@"%@", str);
	
	
    [pool drain];
    return 0;
}

 运行结果:

 

2012-06-24 23:18:51.394 demo8[412:707] one

2012-06-24 23:18:51.397 demo8[412:707] two

2012-06-24 23:18:51.398 demo8[412:707] three

2012-06-24 23:18:51.399 demo8[412:707] four

2012-06-24 23:18:51.401 demo8[412:707] five

2012-06-24 23:18:51.401 demo8[412:707] one two three four five

 

数组的插入:

NSArray只能管理OC的对象,它管理的这些对象可以是不同类型的。

数组对每一个对象具有拥有权。

 

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	//往数组中插入内容
	NSMutableArray* array1 = [NSMutableArray arrayWithCapacity:0];
	[array1 addObject:@"one"];
	NSLog(@"%@", array1);
    
	[array1 addObject:@"three"];  //都是插在末尾
	NSLog(@"%@", array1);
	
	[array1 insertObject:@"two" atIndex:1];  //插入索引为几的位置
	for(NSString* obj in array1)
	{
		NSLog(@"%@", obj);
	}
	
	//移除
	[array1 removeObjectAtIndex:2];
	NSLog(@"%@", array1);
	
	[pool drain];
    return 0;
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值