Foundation——字符串

来源:互联网 发布:mac中文字体下载 编辑:程序博客网 时间:2024/04/30 00:01

字符串

一、不可变字符串的创建的几种方法

    1、字符串的创建

NSString *str1 = @“i love panda”;NSString *str2 = [NSString StringWithFormate:@“i am %d”, 10];//将字符串转为数字。 NSStirng *str3 = [NSString alloc] initWithFormate:@“i am %d”, 10];

    2、将c语言字符串,转成OC字符串,参数字符串无序加@,因为是c语言字符串

 NSString *str4 = [[NSString alloc] initWithUTFString:“i love Panda”];

   3、将OC语言字符串转成c语言字符串

const char *c = [str UTF8String];memcpy(字符数组, [strUTF8String], length);转为字符数组

   4、传文件绝对路径,从文件中取出字符串NSUTF8StringEncoding

NSString *str5 = [[NSString alloc] initWithContentOFFile:@“/文件绝对路径” encoding:NSUTF8StringEncoding error:nil];

   5、资源路径URL

//协议头://路径  //file://路径  本地资源 //ftp://路径   ftp服务器资源 //http://weibo.com/a.png   网络资源

  6、写内容到文件

[@“wirte to \n file” wirteToFile:@“/apple/a.txt” automically:YES encoding:NSUTF8StringEncoding error:nil]; [@“wirte to \n URL” wirteToURL:资源路径 automically:YES encoding:NSUTF8StringEncoding error:nil];

二、NSMutableString可变字符串

   它是NSString的子类,所以以上方法NSMutalbeString都能用

    1、字符串的拼接,下面的代码会自动发字符串的内容拼接到可辨字符串的后面,前提是str是可变字符串

 [str appendString:@“i love panda”];

   2、删除某一范围内的内容

NSRange r = [str RangeOfString:@“love”];//搜索字符串 [str deleteCharactersInRange:r]; substringWithRange//截取某一范围字符串

  3、replace某个范围内的所有字符串,有两个方法

 replaceCharactersInRange:NSRange withString:@""//把这个范围内的字符串,无论多长,替换成后面的字符串。 [strreplaceOccurrencesOfString:@"do"withString:@"fuck"options:NSCaseInsensitiveSearchrange:rang2];//把某一范围内重复的字符串替换掉

4、 把两个字符串拼接返回一个新的字符串

NSString *str = [s1 StringByAppendingString:@“i am"];
0 0