如何读取文本文件,将其转换为字符串,然后使用参数

时间:2014-12-03 10:42:41

标签: ios objective-c nsstring arguments

说如果我有一个字符串="有%@ apples,我吃了%@。现在我有%@ apples"在文本文件" Apples.txt"。这就是我从中提取文本的方法。

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

现在我如何将参数传递给它,使它看起来像这样: "有%@ apples,我吃了%@。现在我有%@ apples",x,y,x-y

我确信使用带有参数的NString可以解决这个问题吗?运用 带有本地参数函数的NSString?否则我将不得不在file.m

中输入我的所有文本

这对我的应用非常重要。

2 个答案:

答案 0 :(得分:1)

您可能正在寻找[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);

<强> 输出:

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

答案 1 :(得分:-1)

使用+ stringWithFormat:

这是Apple reference