问题
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