• Foundation框架之NSString



    1) NSString : 不可变字符串

       NSMutableString : 可变字符串,是NSString的子类。

    2) 创建方式

       NSString *s1 = @”itcast”;

       NSString *s2 = [NSString stringWithFormat:@"My age is%d and no is %d and name is %@", age, no, name];

       NSString *s3 = [[NSString alloc]initWithString:@"jack"];

       NSString *s4 = [[NSString alloc] initWithFormat:@"ageis %d", 10];

       // NSUTF8StringEncoding 用到中文就可以用这种编码

       NSString *s5 = [[NSString alloc]initWithContentsOfFile:@"/Users/apple/Desktop/1.txt"encoding:NSUTF8StringEncoding error:nil];

       // URL : 资源路径(协议头://路径)

       // file://

       // ftp://

       // http://weibo.com/a.png

       // NSURL *url = [[NSURL alloc] initWithString:@"file:///Users/apple/Desktop/1.txt"];

       NSURL *url = [NSURL fileURLWithPath:@"/Users/apple/Desktop/1.txt"];

       NSString *s6 = [[NSString alloc] initWithContentsOfURL:urlencoding:NSUTF8StringEncoding error:nil];

       NSString *s7 = [s2 stringByAppendingString:@" 1112"];

       一般都会有一个类方法跟对象方法配对

       [NSURL URLWithString:<#(NSString *)#>];

       [NSString stringWithFormat:@""];

       [NSString stringWithContentsOfFile:<#(NSString *)#>encoding:<#(NSStringEncoding)#> error:<#(NSError *__autoreleasing*)#>];

    3) C字符串与OC字符串转换

       // C字符串 --> OC字符串

       NSString *s7 = [[NSString alloc]initWithUTF8String:"jack"];

       // OC字符串 --> C字符串

       const char *cs = [s4 UTF8String];

    4) 字符创导出

       [@"Jack Jack"writeToFile:@"/Users/apple/Desktop/my.txt" atomically:YESencoding:NSUTF8StringEncoding error:nil];

       NSString *str = @"4234234";

       NSURL *url = [NSURL fileURLWithPath:@"/Users/apple/Desktop/my2.txt"];

       [str writeToURL:url atomically:YESencoding:NSUTF8StringEncoding error:nil];

    5) NSMutableString常用方法

       NSMutableString *s1 = [NSMutableStringstringWithFormat:@"my age is 10"];

       // 拼接内容到s1的后面

       [s1 appendString:@" 11 12"];

       // 获取is的范围

       NSRange range = [s1 rangeOfString:@"is"];

       [s1 deleteCharactersInRange:range];

    6) NSString输出:

       NSLog(@”我在%@上课”,str);

    7) 获取当前对象的长度:

       [str length];

       字符串length方法返回的是字符串的字数(空格算一个字)。

  • 相关阅读:
    CF1442E. Black, White and Grey Tree
    CF1442D. Sum
    CF1444D. Rectangular Polyline
    arc107F
    外心与垂心关系
    CF1434E. A Convex Game
    CF1434D. Roads and Ramen
    arc106E
    arc106F
    CF704E. Iron Man
  • 原文地址:https://www.cnblogs.com/coderkl/p/4320310.html
Copyright © 2020-2023  润新知