如何读取文本文件,把它变成一个字符串,然后使用它的参数 [英] How to read a text file ,turn it into a string, then using arguments on it
问题描述
说,如果我有一个字符串=有%@苹果,我就吃%@。现在我有%@苹果,在文本文件Apples.txt。这是我将如何从中提取文本。
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];
现在我怎么传递参数给它,所以它看起来是这样的:
有%@苹果,我就吃%@。现在我有%@苹果,X,Y,X-Y
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
我相信有解决这个使用NString带有参数的方法吗?运用
当地参数函数的NSString?否则我将不得不输入所有我的文字在file.m
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.
推荐答案
您可能正在寻找 [的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".
这篇关于如何读取文本文件,把它变成一个字符串,然后使用它的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!