Object-c学习之路七(oc字符串操作)
// // main.m // NSString // // Created by WildCat on 13-7-25. // Copyright (c) 2013年 wildcat. All rights reserved. // #import <Foundation/Foundation.h> #pragma mark 创建字符串 void testCreat(){ NSString *str=@"你好。"; NSLog(@"str :%@",str); NSString *str2=[NSString stringWithUTF8String:"哈哈哈"]; NSLog(@"str2 :%@",str2); NSString *str3=[[NSString alloc] initWithString:@"测试3"] ; NSLog(@"str3 :%@",str3); } #pragma mark 字符串的搜索 void search(){ NSString *str=@"123456456.txt"; NSLog(@"是否以 123 开头:%i",[str hasPrefix:@"123"]); NSLog(@"是否以 txt 结尾:%i",[str hasSuffix:@"txt"]); //从前向后搜索 NSRange range=[str rangeOfString:@"456"]; if (range.location==NSNotFound) { NSLog(@"未找到"); }else{ NSLog(@"找到的范围是:%@",NSStringFromRange(range)); } //从后向前搜索 range=[str rangeOfString:@"456" options:NSBackwardsSearch ]; NSLog(@"找到的范围是:%@",NSStringFromRange(range)); } #pragma mark 字符串截取 void mysubString(){ NSString *str=@"123456789"; //从第6个位置开始截取 NSLog(@"%@",[str substringFromIndex:6]); //截取到第6个位置 NSLog(@"%@",[str substringToIndex:6]); //随便截取一段字符串 NSLog(@"%@",[str substringWithRange:NSMakeRange(1, 3)]); NSString *str2=@"1-2-a-b-c"; //字符串分割 NSArray *array=[str2 componentsSeparatedByString:@"-"]; NSLog(@"%@",array); } #pragma mark 与路径相关 void stringWithPath(){ //快速创建一个自动释放的数组 NSMutableArray *array=[NSMutableArray array]; [array addObject:@"User"]; [array addObject:@"Wildcat"]; [array addObject:@"APP"]; //通过一个数组创建一个路径字符串 NSString *path=[NSString pathWithComponents:array]; NSLog(@"Path is:%@",path); //把一个路径截取为数组 NSArray *apath=[path pathComponents]; NSLog(@"Array is;%@",apath); //删除最后一个目录 NSLog(@"Array is;%@",[path stringByDeletingLastPathComponent]); //拼接一个路径 NSLog(@"Array is;%@",[path stringByAppendingPathComponent:@"123.txt"]); } #pragma mark 其他用法 void other(){ NSString *str=@"123"; int a=[str intValue];//转化为整数 NSLog(@"%i",a); //计算字数而不是字符数 NSLog(@"length=%zi",[@"我是字符串12345" length]); //返回对应的字符 unichar c=[@"abc123" characterAtIndex:1]; NSLog(@"第2个字符是:%c",c); //返回C语言字符串 const char *s=[@"abc" UTF8String]; NSLog(@"C语言字符串是:%s",s); } #pragma mark 主函数 int main(int argc, const char * argv[]) { @autoreleasepool { // testCreat(); // creatWithContent(); //writeToFile(); //search(); //调用截取字符串函数 //mysubString(); //stringWithPath(); other(); } return 0; }