您的位置:首页 > 职场人生

黑马程序员-oc基础-Foundation中NSString类型的一些用法

2015-07-13 11:32 363 查看
------Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! ------

1.创建方式:

1  NSString *s=@"abc";
2
3  NSString *s=[[NSString alloc] initWithString:@"aab"]
4
5  NSString *s=[[NSString alloc] initWithStringFormat:@"%d",10]


 

 2.oc字符串和c字符串的转化

1    // c  -》  oc:
2    NSString *s=[[NSString alloc]initWithUTF8String:"jack"]
3
4    // oc ->    c:
5    const char *ch=[s UTF8String]


 

3.读取文件操作

  1,读取文件资源的内容

NSString *s=[[NSString alloc]initWithContentOfFile:@"/User/..." encoding:NSUTF8StringEncoding error:nil]


  2.读取url资源内容

 NSURL  *url=[[NSURL alloc]initWithString:@"file:///User..."]

    NSString *s=[[NSString alloc]initWithContentOfURL:url encoding:NSUTF8StringEncoding error:nil]


  注:url表示资源,通常格式:协议头://路径

    本地文件:file:///User/..

    网络资源:http://...     ,ftp://...

4.创建file资源url

  [NSURL fileURLWithPath:@"/User.."]//如果是file的话 省略的file://协议头

5.以上的对象调用方法十分的麻烦,代码量多,所有xcode又有新的实现方式

       系统自带的对象方法,一般都有一个类方法与之对应 eg.

[NSString stringWithFormat:@""]

  [NSString stringWithUTF8:""]//c->oc

  [NSString stirngWithContentOfFile:]

  [NSURL URLWithString:@""]//讲NSString路径转成了NSURL


6.将字符串写入文件

  1.直接写入本地文件

 [@"dfaf"  writeToFile:@"/User..." atomically:YES encoding:NSUTF8StringESncoding error:nil]


    参数atomically为yes是,表示写入文件过程中出错的话,这个文件就不会写入成功,也就是不保存,为no还是会继续保存

  2.写入资源文件

    NSURL *url=[NSURL fileURLWithPath:@"/.."]  

    [@"dgddg" writeToURL:url atomically:YES encoding:NSUTF8StringESncoding error:nil]


 7.其他的方法:

  1.将字符串中某个范围内的字符串替换成指定的字符串

    NSRange  *range=[@"jnkfhjkudhf" rangeOfString:@"fh"]

    NSString *str=[@"jnkfhjkudhf" stringByReplacingCharactersInRange:range  withString:@"th"]


  2.判断字符串是否相等

Bool b=[@"abc" isEqualToString:@"abc"]


  3.转化大小写

NSString *str=[@"ABC" lowerCaseString]


  4.获取文件后缀名    

NSString *str=[@"abc.txt" pathExtension]


  5.按照指定的字符串将字符串分割成字符串数组

NSArray *arr=[@"2015-10-9" componentsSeparatedByString:@"-"]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: