字符串创建 最简单的字符串创建方式 NSString *str = @”itcast”; 对象方法 以一定的格式定义字符串 NSString *s1 = [[NSString alloc] initWithFormat:@”My name is %@”, str]; C字符串->OC字符串 NSString *s2 = [[NSString alloc] initWithUTF8String:”jack”]; OC字符串->C字符串 char *c = [s2 UTF8String]; 字符串->数字 NSString *s1 = @”10”; int s = [s1 intValue]; 数字->字符串 NSString *s2 = [[NSString alloc] initWithInt: s]; 某个范围的子字符串 NSString *s5 = @”232700198351038938”; NSString *s1 = [s5 substringWithRange: NSMakeRange(0, 4)]; // 取出身份证字符串中前四位 某个索引的子字符串 NSString *s2 = [s5 substringFromIndex: 17]; // 取出身份证字符串中最后一位 某个索引的字符 char c = [s5 characterAtIndex: 17]; // 取出身份证字符串中的最后一位字符 大写->小写 NSString *name = [@“Rose” lowercaseString]; 判断两个字符串是否相同 bool [s1 isEqualToString:@”4201”]; 读取文件内容 NSString *s3 = [[NSString alloc] initWithContentsOfFile: (NSString *) encoding:(NSStringEncoding) error: (NSError *_autoreleasing *)]; NSString *s3 = [[NSString alloc] initWithContentsOfFile: @”/Users/apple/Desktop/abc.txt” encoding: NSUTF8StringEncoding error: nil] 读取资源内容 NSString *s4 = [[NSString alloc] initWithContentsOfURL: (NSURL *) encoding: (NSStringEncoding) error: (NSError *_autoreleasing *)]; NSURL *url = [[NSURL alloc] initWithString: @”file:///Users/apple/Desktop/abc.txt”; NSString *s4 = [[NSString alloc] initWithContentsOfURL: url encoding: NSUTF8StringEncoding error: nil]; 类方法 以一定的格式创建字符串 NSString *s1 = [NSString stringWithFormat:@”My name is %@”, str]; 读取文件内容 NSString s2 = [NSString stringWithContentsOfFile:@”/Users/apple/Desktop/abc.txt” encoding: NSUTF8StringEncoding error: nil]; 读取资源内容 // URL为指定文件时不需要加协议头 NSURL *url1 = [NSURL filURLWithPath: @”/USers/apple/Desktop/abc.txt”]; // URL的一般定义方式要加协议头 NSURL *url2 = [NSURL URLWithString: @”file: ///Users/apple/Desktop/abc.txt”]; NSString s3 = [NSString stringWithContentsOfURL: url encoding: NSUTF8StringEncoding error: nil] 字符串的写入 NSString *str = @”itcast”; 将字符串写入文件 [str writeToFile: @”/Users/apple/Desktop/abc.txt” atomically: YES encoding: NSUTF8StringEncoding error: nil]; 将字符串写入URL资源 NSURL *url = [NSURL fileURLWithPath:@”/Users/apple/Desktop/abc.txt”]; [str writeToURL: url atomically: YES encoding: NSUTF8StringEncoding error: nil]; 可变字符串 NSMutableString *s1 = [[NSMutableString alloc] initWithString:@””]; NSMutableString *str = [NSMutableString stringWithFormat:@”age is 10”]; 拼接字符串 NSMutableString *s1 = [str appendString: @”i love oc”]; 删除字符串 NSRange r1 = [s1 rangOfString:@”is”]; NSMutableString *s2 = [s1 deleteCharactersInRange: r1]; 或者 NSMutableString *s2 = [s1 deleteCharactersInRange: NSMakeRange(4, 2)];
|