---
title: "NSString 截取，文件读取【转】 "
author: "fantom"
date: "2013-01-16T07:18:06Z"
tags: []
categories: ["移动开发"]
slug: "nsstring"
draft: false
lastmod: "2013-01-15T10:18:52Z"
id: 1769958
url: "https://fantom.iteye.com/blog/1769958"
---

【转】<http://www.cnblogs.com/csj007523/archive/2012/07/15/2592302.html>
小结：
1）componentsSeparatedByString:截取指定字符串；
2) pathForResource：获取程序运行时目录
3)  objectAtIndex:获取当前索引的字符串；
4)  rangeOfString:获取指定短字符串在长字符串中的开始，结尾索引值；
5) stringWithContentsOfFile：按行读取文件
6) componentsSeparatedByString:@"\n"];换行分割字符串；
7) NSEnumerator *nse = ;	将数组转换为NSEnumerator，可向前读取数据；
8)  nextObject：读取下一行数据；
 

```java
-(void) splitString
{
	NSString *animals = @"dog#cat#pig";
	//将#分隔的字符串转换成数组
	NSArray *array = [animals componentsseparatedbystring:@"#"];
	NSLog(@"animals:%@",array);
	
	//获取程序运行时目录
	NSString *escapedPath = [[nsbundle mainbundle] pathForResource:@"info" ofType:@"plist"];
	NSArray *strings = [escapedpath componentsseparatedbystring: @"/"];
	NSString *tmpFilename  = [strings objectatindex:[strings count]-1];
	NSRange iStart = [escapedpath rangeofstring : tmpfilename];
	NSString *runtimeDirectory = [escapedpath substringtoindex:istart.location-1];
	NSLog(@"runtimeDirectory:%@",runtimeDirectory);
	
	//按行读取文件	
	NSString *tmp;
	NSArray *lines = [[nsstring stringwithcontentsoffile:@"test.txt" encoding:nil error:nil] 
					  componentsSeparatedByString:@"\n"];	
	NSEnumerator *nse = [lines objectenumerator];	
	while(tmp = [nse nextobject]) {
		NSLog(@"tmp:%@", tmp);
	}
	
}

```