#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSNumber* n1 = [[NSNumber alloc] initWithInt:100];//使用实例方法创建对象,需要手动释放
int int1 = [n1 intValue];
NSNumber* n2 = [NSNumber numberWithInteger:100];//使用类方法创建对象,本身发送了autorease消息
NSInteger int2 = [n2 integerValue];
if([n1 isEqualToNumber:n2])
{
NSLog(@"n1 is same to n2");
}
else
{
NSLog(@"n1 is different to n2");
}
if([n1 compare:n2] == NSOrderedAscending)
{
NSLog(@"n1 < n2");
}
if([n1 compare:n2] == NSOrderedSame)
{
NSLog(@"n1 == n2");
}
if([n1 compare:n2] == NSOrderedDescending)
{
NSLog(@"n1 > n2");
}
//创建字符串的几种方法:
NSString* str = @"hello world";
NSString* strr = @"welcome";
NSString* str1 = [NSString stringWithFormat:@"%@",[NSDate date]];//返回现在的时间
NSString* str2 = [NSString stringWithString:str1];
NSLog(@"%ld",[str length]);//打印字符串的长度
NSString* str3 = [str stringByAppendingString:strr];//hello worldwelcome //连接两个字符串,生成新的字符串
//大小写转换 不会影响原来的字符串
NSLog(@"%@",[[str3 uppercaseString] lowercaseString]);
NSLog(@"%@",str3);
//比较字符串
//isEqualToString: 比较两个字符串是否相等
//compare: 比较两个字符串的大小 不忽略大小写
//caseInsensitiveCompare: 比较两个字符串的大小,不区分大小写
if([str1 isEqualToString:str2])
{
NSLog(@"str1 is equal to str2");
}
if([str compare:strr] == NSOrderedAscending)
{
NSLog(@"str < strr");
}
else if([str compare:strr] == NSOrderedSame)
{
NSLog(@"str == strr");
}
else
{
NSLog(@"str > strr");
}
//求子串
//substringToIndex:(int)index 返回一个子串,从接受者首字符开始到index - 1; 从0开始计算
//substringFromIndex:(int)index 返回一个子串,从index开始,到结尾
//substringWithRange:(NSRange)range; 返回指定返回的子串
/*NSRange 是一个结构体,成员有:unsigned int location; unsigned int length;
NSRange range;
range.location = 8;//位置
range.length = 6;//长度
NSString* str = [str1 substringWithRange:range];//返回str1中位置从8开始,长度为6的子串
或者使用下面的方法(与上面等价)
NSString* str = [str1 substringWithRange:NSMakeRange(8,6)];
//NSMakeRange(8,6);返回一个NSRange变量,里边的参数(8,6)是分别对应着NSRange的location和length
*/
//rangeOfString:(NSString*)str1; 如果指定的字符串(str1)在接收者里找到,返回指定字符串的Range(位置和长度),如果未找到,则将返回的location设置未NSNotFound,所以在调用rangeOfString:消息时,下一步就会判断range.location是否未NSNotFound。
NSString* str4 = [str3 substringToIndex:7];//hello w (0 --> 6)
NSString* str5 = [str3 substringFromIndex:9];//ldwelcome (从第9个一直到结尾)
NSRange range;
range.location = 8;
range.length = 6;
NSString* str6 = [str3 substringWithRange:range];//rldwel
NSString* str7 = [str3 substringWithRange:NSMakeRange(8, 6)];//rldwel
NSRange range2;
range2 = [str3 rangeOfString:@"rlwel"];
if(range2.location != NSNotFound)
{
NSLog(@"location = %ld,length = %ld",range2.location,range2.length);
}
if(range2.location == NSNotFound)
{
NSLog(@"not found!");
}
[n1 release];
}
return 0;
}