Objective-C字符串处理

 NSLog(@"字符串处理");

 

//获得字符串长度

NSString* str1=@"MAC OS Pro";

NSLog(@"长度是 %d",[str1 length]);

//两个字符串连接

NSString* str2=@"MAC OS Pro";

NSString* str3=@" Leopard";

NSString* str4=[str2 stringByAppendingString:str3];

NSLog(str4,nil);

NSString* str5=[str2 stringByAppendingFormat:@" %d",10];

NSLog(str5,nil); 

//可修改字符串

NSMutableString* string=[NSMutableString string];

[string appendString:@"Mac"];

[string appendString:@" OS"];

[string appendString:@" X"];

NSLog(string,nil); 

//插入字符串

NSMutableString* string1=[NSMutableString stringWithFormat:@"Mac X"];

[string1 insertString:@"OS " atIndex:4];

NSLog(string1,nil);

//删除字符串

NSMutableString* string2=[NSMutableString stringWithFormat:@"删除字符串"];

[string2 deleteCharactersInRange:NSMakeRange(02)];

NSLog(string2,nil);

//字符串比较

BOOL result;

result=[string isEqualToString:string1];

NSLog(@"%d",result,nil);

//比较前置串与后置串

NSString* string3=@"Mac Pro";

NSString* string4=@"Mac OS";

//判断是否以Mac开头

result=[string3 hasPrefix:@"Mac"];

NSLog(@"%d",result,nil);

//判断是否以OS结尾

result=[string4 hasSuffix:@"OS"];

NSLog(@"%d",result,nil);

NSString* string5=@"This is Mac OS X";

//检索字符串

NSRange range;

range=[string5 rangeOfString:@"Mac OS"];

if (range.location!=NSNotFound

{

//得到字符串的位置和长度

NSLog(@"%d,%d",range.location,range.length);

}

else 

{

NSLog(@"没有发现",nil);

}

//抽取部分字符串

NSString* string6=@"This is Mac OS X";

NSString *nstr1,*nstr2,*nstr3;

//从开头抽取字符串

nstr1=[string6 substringToIndex:4];

NSLog(nstr1,nil);

//抽取末位位置的字符串

nstr2=[string6 substringFromIndex:8];

NSLog(nstr2,nil);

//抽取指定范围的字符串

nstr3=[string6 substringWithRange:NSMakeRange(5,2)];

NSLog(nstr3,nil);

 

 

//结果

2011-10-20 14:05:43.940 StringProcessing[1870:1307] 字符串处理

2011-10-20 14:05:43.942 StringProcessing[1870:1307] 长度是 10

2011-10-20 14:05:43.943 StringProcessing[1870:1307] MAC OS Pro Leopard

2011-10-20 14:05:43.943 StringProcessing[1870:1307] MAC OS Pro 10

2011-10-20 14:05:43.944 StringProcessing[1870:1307] Mac OS X

2011-10-20 14:05:43.945 StringProcessing[1870:1307] Mac OS X

2011-10-20 14:05:43.945 StringProcessing[1870:1307] 字符串

2011-10-20 14:05:43.946 StringProcessing[1870:1307] 1

2011-10-20 14:05:43.946 StringProcessing[1870:1307] 1

2011-10-20 14:05:43.947 StringProcessing[1870:1307] 1

2011-10-20 14:05:43.947 StringProcessing[1870:1307] 8,6

2011-10-20 14:05:43.948 StringProcessing[1870:1307] This

2011-10-20 14:05:43.948 StringProcessing[1870:1307] Mac OS X

2011-10-20 14:05:43.949 StringProcessing[1870:1307] is

 

以备用到的时候查看

 
posted @ 2012-04-26 14:21  wgw8299  阅读(166)  评论(0编辑  收藏  举报