标签:
#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;
}
加微信txs8882909 大家一起讨论
标签:
原文地址:http://www.cnblogs.com/txsx/p/5494619.html