Parsing a .txt or html file into a string in the i

2019-08-27 18:09发布

问题:

So, what I'm trying to do, is take a .txt or html file, being able to search through it, and grab a piece of text from file, place it into a string and finally adding it into a textView.

Each couple of piece of text will be divided like this:

001:001 Text1

001:002 Text2

001:003 Text3

002:001 Text1a

002:002 Text1b

... and so on

So essentially you would search the text for those numbers, and it would grab the text only. Is there a way to do that using objective C and using it on a iPhone app?

回答1:

Use

NSString *pathToDefaultPlist = [[NSBundle mainBundle] pathForResource:@"TextFile" ofType:@"text"];

to load text file. Then:

+ (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error

this function to load the text file in String. Then use NSString function to divide the token :)



回答2:

In addition to the [NSString stringWithContentsOfFile:encoding:error] to get the text of the file, your textView should have a setStringValue method.

so I'd do something like this:

NSString *pathToTextFile;
NSError  *readError;
NSString *fileData = [NSString stringWithContentsOfFile:pathToTextFile
                               encoding:(appropriate encoding for your file)
                               error:*readError]

[textView setStringValue:fileData];

This might need a little massaging, I'm at work and don't have my Mac to verify the method signatures etc. But that's the general idea.