[IOS] Objective-C 字符处理函数
//获得字符串长度
NSString*str1=@"MACOSPro";
NSLog(@"长度是%d",[str1length]);
//两个字符串连接
NSString*str2=@"MACOSPro";
NSString*str3=@"Leopard";
NSString*str4=[str2stringByAppendingString:str3];
NSLog(str4,nil);
NSString*str5=[str2stringByAppendingFormat:@"%d",10];
NSLog(str5,nil);
//可修改字符串
NSMutableString*string=[NSMutableStringstring];
[stringappendString:@"Mac"];
[stringappendString:@"OS"];
[stringappendString:@"X"];
NSLog(string,nil);
//插入字符串
NSMutableString*string1=[NSMutableStringstringWithFormat:@"MacX"];
[string1insertString:@"OS"atIndex:4];
NSLog(string1,nil);
//删除字符串
NSMutableString*string2=[NSMutableStringstringWithFormat:@"删除字符串"];
[string2deleteCharactersInRange:NSMakeRange(0,2)];
NSLog(string2,nil);
//字符串比较
BOOLresult;
result=[stringisEqualToString:string1];
NSLog(@"%d",result,nil);
//比较前置串与后置串
NSString*string3=@"MacPro";
NSString*string4=@"MacOS";
//判断是否以Mac开头
result=[string3hasPrefix:@"Mac"];
NSLog(@"%d",result,nil);
//判断是否以OS结尾
result=[string4hasSuffix:@"OS"];
NSLog(@"%d",result,nil);
NSString*string5=@"ThisisMacOSX";
//检索字符串
NSRangerange;
range=[string5rangeOfString:@"MacOS"];
if(range.location!=NSNotFound)
{
//得到字符串的位置和长度
NSLog(@"%d,%d",range.location,range.length);
}
else
{
NSLog(@"没有发现",nil);
}
//抽取部分字符串
NSString*string6=@"ThisisMacOSX";
NSString*nstr1,*nstr2,*nstr3;
//从开头抽取字符串
nstr1=[string6substringToIndex:4];
NSLog(nstr1,nil);
//抽取末位位置的字符串
nstr2=[string6substringFromIndex:8];
NSLog(nstr2,nil);
//抽取指定范围的字符串
nstr3=[string6substringWithRange:NSMakeRange(5,2)];
NSLog(nstr3,nil);
//结果
2011-10-2014:05:43.940StringProcessing[1870:1307]字符串处理
2011-10-2014:05:43.942StringProcessing[1870:1307]长度是10
2011-10-2014:05:43.943StringProcessing[1870:1307]MACOSProLeopard
2011-10-2014:05:43.943StringProcessing[1870:1307]MACOSPro10
2011-10-2014:05:43.944StringProcessing[1870:1307]MacOSX
2011-10-2014:05:43.945StringProcessing[1870:1307]MacOSX
2011-10-2014:05:43.945StringProcessing[1870:1307]字符串
2011-10-2014:05:43.946StringProcessing[1870:1307]1
2011-10-2014:05:43.946StringProcessing[1870:1307]1
2011-10-2014:05:43.947StringProcessing[1870:1307]1
2011-10-2014:05:43.947StringProcessing[1870:1307]8,6
2011-10-2014:05:43.948StringProcessing[1870:1307]This
2011-10-2014:05:43.948StringProcessing[1870:1307]MacOSX
2011-10-2014:05:43.949StringProcessing[1870:1307]is