NSString -----------通过URL读取文件------------- 什么是URL: URL是统一资源定位符。URI是统一资源标识符。 例如网上一张图片名为a.jpg,那么a.jpg就是统一资源标识符。而在网上打开这张图片时,网址叫做统一资源定位符 URL的格式 基本URL包含 协议,主机域名(服务器名称/IP地址),路径 例如: NSURL *url = [NSURL URLWithString:@"file:///Users/sy/Desktop/test.txt"]; // 此写法不支持中文 //NSURL *url = [NSURL fileURLWithPath:@"/Users/sy/Desktop/哈哈/test.txt"]; // 此写法支持中文 NSError *err = nil; NSString *str = [NSString stringWithContentsOfURL: url encoding:NSUTF8StringEncoding error:&err]; If(err != nil){ NSLog(@"%@",[err localizedDescription]); } else { NSLog(@"%@",str); } ------------通过NSURL对象来写入文件------------ NSString *str = @"你好"; NSURL *url = [NSURL fileURLWithPath:@"/Users/sy/Desktop/哈哈/test.txt"]; NSError *err = nil; [str writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&err]; If(err != nil){ NSLog(@"%@",[err localizedDescription]); } else { NSLog(@"写入成功"); }
----------字符串常用方法--------------- 1> //转换大写 NSString *s1 = @"Hello China"; S1 = [s1 uppercaseString]; NSLog(@"%@",s1); 2> //转换小写 NSString *s1 = @"Hello China"; S1 = [s1 lowercaseString]; NSLog(@"%@",s1); 3> //把每个单词的首字母转换成大写 NSString *s1 = @"heLLO cHiNa"; S1 = [s1 capitalizedString]; NSLog(@"%@",s1); //输出结果为 Hello China 4> //判断两个字符串是否相等 NSString *s1 = @"123"; NSString *s2 = [NSString stringWithFormat:@"%d",123]; //一个在常量区,一个在堆区,地址不同 NSLog(@"s1==s2的结果是%d",(s1==s2)); // 结果为0,因为使用==判断的是地址是否相同 //判断两个字符串的内容是否相同 BOOL b = [s1 isEqualToString:s2]; //比较的是asc码 NSLog(@"%d",b); 5> //比较字符串 NSString *s1 = @"abc"; NSString *s2 = @"cba"; NSComparisonResult result = [s1 compare:s2]; //从首字母开始比较asc码 //NSComparisonResult result = [s1 caseInsensitiveCompare:s2];// 不敏感的比较:忽略大小写比较 Switch (result) { case NSOrderedAscending: NSLog(@"s1<s2"); break; case NSOrderedDescending: NSLog(@"s1>s2"); break; case NSOrderedSame: NSLog(@"s1==s2"); break; } 6> //检查一个字符串是否以XXX开头 NSString *s1 = @"http://www.baidu.com"; BOOL b = [s1 hasPrefix:@"http"]; NSLog(@"%d",b); 7> //检查一个字符串是否以XXX结尾 NSString *s1 = @"http://www.baidu.com"; BOOL b = [s1 hasSuffix:@".com"]; NSLog(@"%d",b); 8> //检查一个字符串里是否包含了XXXX NSString *s1 = @"北京天安门"; NSRange range = [s1 rangeOfString:@"天安门"]; // 默认情况下只查找第一个XXX NSLog(@"location= %ld,length = %ld",range.location,range.length); //若找不到,location == NSNotFound length==0
|