OC字符串基本使用

NSString*str1 =@”This is string A”;
NSString*str2 =@”This is string B”;

NSString*res;
NSComparisonResultcompareResult;
NSRangesubRange;

//计算字符串中的字符
NSLog(@”Length of str1:%lu”,[str1length]);

//将一个字符串复制到另一个字符串
res = [NSStringstringWithString:str1];
NSLog(@”copy:%@”,res);

//将一个字符串复制到另一个字符串的末尾

str2 = [str1stringByAppendingString:str2];
NSLog(@”Concatentation:%@”,str2);

//验证两个字符串是否相等
NSLog(@”*****验证两个字符串是否相等*****”);
if([str1isEqualToString:str2] ==YES)
{
NSLog(@”str1 == str2″);
}else{
NSLog(@”str1 != str2″);
}

//验证一个字符串是否小于、等于、大于另外一个字符串
NSLog(@”******验证一个字符串是否小于、等于、大于另外一个字符串**********”);
compareResult = [str1compare:str2];
if(compareResult ==NSOrderedAscending)
{
NSLog(@”str1 < str2″);
}
elseif(compareResult ==NSOrderedSame)
{
NSLog(@”str1 == str2″);
}
else{
NSLog(@”str1 > str2″);
}
NSLog(@”******将字符串转换为大写********”);
//将字符串转换为大写
res = [str1uppercaseString];
NSLog(@”Uppercase conversion:%s”,[resUTF8String]);

//将字符串转换为小写

res = [str1lowercaseString];
NSLog(@”Lowercase conversion:%@”,res);
NSLog(@”Original string:%@”,str1);

//从字符串中提取前3个字符
res = [str1substringToIndex:3];
NSLog(@”First 3 chars of str1:%@”,res);

//提取从索引5开始直到结尾的子字符串
res = [str1substringFromIndex:5];

       NSLog(@”Chars from index 5 of str1:%@”,res);
         //提取字符串的后4位
        res = [str1 substringFromIndex:str1.length – 4];

//提取从索引5开始到索引13的子字符串
res = [str1substringWithRange:NSMakeRange(8,6)];
NSLog(@”Chars from index 8 through 13:%@”,res);

//从另一个字符串中查找一个字符串
subRange = [str1rangeOfString:@”string A”];
NSLog(@”String is at index %lu,length is %lu”,subRange.location,subRange.length);

subRange = [str1rangeOfString:@”string B”];
if(subRange.location==NSNotFound)
{
NSLog(@”String is found”);
}
else
{
NSLog(@”String is at index %lu,length is %lu”,subRange.location,subRange.length);
}

分享到: 更多
Separator image Posted in IOS.