How to read a text file ,turn it into a string, then using arguments on it

妖精的绣舞 提交于 2019-12-11 08:01:04

问题


Say If I had a string = "There were %@ apples,I ate %@. Now I have %@ apples" in text file "Apples.txt". This is how I will extract the text from it.

NSString *path = [[NSBundle mainBundle] pathForResource:@"Apples" ofType:@"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

Now how do I pass the arguments to it so it looks like this: "There were %@ apples,I ate %@. Now I have %@ apples", x, y, x-y

I am sure there is a way around this using NString with arguments? using NSString with local argument functions? otherwise I will have to type all of my text in the file.m

This very crucial for my app.


回答1:


You are probably looking for [NSString stringWithFormat:...].

Your complete code goes like this :

NSString *path = [[NSBundle mainBundle] pathForResource:@"Apples" ofType:@"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

NSNumber *total = @100;
NSNumber *ate = @34;

NSString *fullString = [NSString stringWithFormat:content,total,ate, @([total integerValue] - [ate integerValue])];

NSLog(@"%@", fullString);

Output:

"There were 100 apples,I ate 34. Now I have 66 apples".



回答2:


Use + stringWithFormat:

Here's the Apple reference



来源:https://stackoverflow.com/questions/27269587/how-to-read-a-text-file-turn-it-into-a-string-then-using-arguments-on-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!