------ android培训、java培训、期待与您交流! ----------
OC基础—结构体、字符串
结构体(NSRange、NSPoint、NSSize、NSRect)
typedef struct _NSRange
{
NSUInteger location;
NSUInteger length;
} NSRanger;
// NSRange创建
NSMakeRange(2, 4);
NSString *s = @"i love oc";
// 查找摸个字符穿在s中的范围
// 如果找不到,length = 0, location = NSNotFound = -1
NSRange range = [s rangeOfString:@"love"];
NSLog(@"loc = %lu, length = %lu", (unsigned long)range.location, (unsigned long)range.length);
type struct _NSPoint
{
CGFloat x;
CGFloct y;
} NSPoint;
CGPoint p1 = NSMakePoint(10, 10);
NSPoint p2 = CGPointMake(20, 20); // 这两种方式都是可以的,但是最常用这一种
typedef struct _NSSize
{
CGFloct width;
CGFloct height;
} NSSize;
NSSize s1 = CGSizeMake(10, 20);
CGSize s2 = NSMakeSize(20, 10);
typedef struct _NSRect
{
NSPoint origin;
NSSize size;
} NSRect;
// x,y,宽,高
CGRect r1 = CGRectMake(0, 0, 50, 100);
CGRect r2 = { {0,0},{100,90}};
CGRect myRect(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
{
CGRect rect;
rect.origin.x = x;
rect.origin.y = y;
rect.size.width = width;
rect.size.height = height;
return rect;
}
// 整个结构体转成字符串
NSString *str = NSStringFromPoint(p1);
NSString *str2 = NSStringFromRect(r1);
// 使用这些函数的前提,包含CoreGraphics框架
// foundation框架是有NextSte架构的
// 比较来两个点的位置是否相同
BOOL b = CGPointEqualToPoint(p1, p2);
BOOL b2 = CGSizeEqualToSize(s1, s2);
// 判断p2在不在r1里面
BOOL b3 = CGRectContainsPoint(r1, p2);
NSString *s1 = @"我是字符串";
这种方法简单明了
NSString *s2 = [[NSString alloc] initWithFormat:@"我是字符串+%d", 10];
NSString *s3 = [[NSString alloc] initWithUTF8String:"我是C字符串"];
char *c = [s3 UTF8String];
NSString *s4 = [[NSString alloc] initWithContentsOfFile:@"/Users/liuthou/Desktop/liye.txt" encoding:NSUTF8StringEncoding error:nil];
// URL:资源路径
// 协议头://路径
// file://
// ftp://
// 万能的!!
NSURL *url = [[NSURL alloc] initWithString:@"file:///Users/liuthou/Desktop/liye.txt"];
NSURL *url3 = [NSURL fileURLWithPath:@"file:///Users/liuthou/Desktop/liye.txt"];
NSString *s5 = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSString *s = [NSString stringWithFormat:@"我是字符串+%d", 10];
// 字符串的导入文件
[@"liye\n hehe23412342134" writeToFile:@"/Users/liuthou/Desktop/liye.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSURL *url = [NSURL URLWithString:@"file:///Users/liuthou/Desktop/liye.txt"];
[@"liye\n 1234567890" writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSMutableString是继承自NSString,所以NSMutableString包含NSString的方法,当然包括创建方式。
NSMutableString的创建:
NSMutableString *s1 = [NSMutableString stringWithFormat:@"name is liye"];
// 拼接内容到s1的后面
[s1 appendSstring:@"12,123"];
// 删除字符串
[s1 deleteCharactersInRange:CGSizeMake(5, 4)];
删除字符串所因为5在内的之后4个字符
。
我们也可以删除指定字符
// 获取删除字符范围
NSRange ranfe = [s1 rangeOfString:@"liye"];
// 删除指定范围字符
[s1 deleteCharactersInRange:range];
------ android培训、java培训、期待与您交流! ----------