oc string基本操作

//创建字符串
NSString* astring = @"This is a String";

//创建空串,给予赋值
NSString* astring =[[NSString alloc]init];
astring = @"This is a String";

NSLog(@"astring:%@",astring);

[astring release];

//使用变量初始化
NSString* name = @"Cross";

NSString* astring = [NSString stringWithFormat:@"My Name is %@",name];

NSLog(@"astring:%@",astring);

//判断是否包含某字符串 检查字符串是否以另一个字符串开头
-(BOOL) hasPrefix:(NSString*)aString{
    
    NSString* String1 = @"NSStringInformation.txt";
    [String1 hasPrefix:@"NSStrng"] == 1?NSLog(@"YES"):NSLog(@"NO");
}
//是否包含其他字符串
 [String1 rangofString:@"This"].length>0

 //从文件读取字符串
 NSString* path = @"astring.txt";
 
 NSString* astring = [[NSString alloc]initWithContentOfFile:path];
 NSLog(@"astring:%@",astring);
 
 //写字符串到文件
 [astring writeToFile:path atomically:YES]; 
 
 //比较字符串
 NSString* astring0 = @"This is a string";
 NSString* astring1 = @"This is a string";
BOOL result = [astring0 isEqualToString:astring1]; 
 NSLog(@"result:%d",result);
 
 //compare方法
 BOOL result = [astring0 compare:astring1] == NSOrderedSame;
 //NSOrderedSame判断两者内容是否相同
 
 //不考虑大小写比较字符串
 BOOL result = [astring0 caseInsensitiveCompare:astring1];
 
 //改变字符串的大小写
 [astring0 uppercaseString];
 [astring0 lowercaseString];
 [astring0 capitailzedString];
 
 //串中查找字串
 NSString* string1 = @"This is a string";
 NSString* string2 = @"string";
 NSRange range = [string1 rangeOfString string2];
 int location = range.location;
 int length = range.length;
 
 //替换字符串
 NSString* astring01 = @"hello 中国";
 NSString* new = [astring01 stringByReplaceOccurencesOfString:@"中国" withString:@"北京"];
 
 //分割字符串成数组
 NSString* s = @"a b c d";
 NSArray* arr = [s componentsSeparatedByString@" "];
 NSLog(@"count = %d",[arr count]);
 
 //字符串数组拼接成字符串
 NSArray* pathArray = [NSArray arrayWithObjects:@"here",@"be",@"dragons",nil];
 NSString* s = [pathArray componentsJoinByString:@""];
 
 //抽取字串
 1:从开头一直截取到指定的位置
 [s substringToIndex:3];
 2:从指定位置开始
 [s substringFromIndex:3];
 3:给出位置长度截取
 [s substringWithRange:NSMakeRange(0,4)];
 
 
 //可变字符串
 //给字符串分配容量
 NSMultableString* ss = [NSMultableString stringWithCapacity:40];
 [ss appendFormat:[NSString stringWithFormat:@",I WILL BE ADDING SOME CHARACTER"]];
 
 //将已有的换成其他的字符串
 [ss setString@"Hello World!"];
 
 //按照给出的范围替换
 [ss replaceCharactersInRange:NSMakeRange(0,3)withString:@"That"];
 
 //从另一个数组拷贝数据到另一个数组
 NSMutableArray* MutableArray = [[NSMutableArray alloc]init];;
 NSArray array = [NSArray arrayWithObjects:@"a",@"b",@"c"];
 
 MutableArray = [NSMutableArray arrayWithArray:array];
 [MutableArray release];
 
 //copy
 id obj;
 NSMutableArray* newArray = [[NSMutableArray alloc]init]
 NSArray* oldArray = [NSArray arrayWithObjects@"a",@"b",nil];
 
 obj = [[oldArray objectAtIndex:0]copy];
 [newArray adObject:obj];
 
 //快速遍历数组
 for(id obj in newArray)
 
 
 
 
 
 
 
 
 

 

posted @ 2013-05-31 11:06  CrossZhu  阅读(329)  评论(0编辑  收藏  举报