1.直接赋值
NSString *name = @"Starain";
2.用已经存在的字符串进行初始化
NSString *name2 = [NSString stringWithString:name];
或者NSString *name3 = [[NSString alloc]initWith String:name];
3.格式化字符串
int age = 20;
NSString *msg =[NSString stringWithFormat:@"name = %@, age = %d",name, age];
4.使用C语言字符串来初始化
NSString *str = [NSString stringWithCString:"C String" ,NSUTF8StringEncoding];
5.求字符串长度
NSString *str1 = @"Starain";
NSUInteger len = [str1 length];
NSLog(@"%lu",(unsignedlong)len);
6.特定位置字符(0开始)
char c1 = [str characterAtIndex:n];
NSLog(@"%c",c1);
第6个位置,就是n=5时。
7.NSString 和NSData转换
常用于客户端项目获取网络数据
①NSString *str3 = @"hello world";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",data);
②NSString *temp = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLof(@"%@",temp);
8.写文件操作
NNString *str = @"要写的内容";
NSString *path = @"/usr/starain/test.txt";//目录,如果没有可自行创建
BOOL result = [str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];//atomically表示是否有临时文件
NSLog(@"%d",result);
9.读文件操作
NSString *newstr = [NSString stringWithContensOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",newstr);
10.字符串中取字符
①NSString *substr1 = [strm subStringToIndex:5];//从头开始取5个字符,取到第6个
NSLog(@"%@",substr1);
②NSString *substr2 = [strm subStringFromIndex:6];//从第7个字符取到末尾
NSLog(@"%@",substr2);
③NSRange r = NSMakeRange(2,3);//从第(2+1)个开始取3个
NSString *substr3 = [strm subStringWithRange:r];
NSLog(@"%@",substr3);
11.类型转换
NSString *age = @"test";
int age1 = [age intvalue];
NSString *PI = @"3.1415";
float PI2 = [PI floatvalue];