Append string with variable

拥有回忆 提交于 2019-12-17 23:39:34

问题


I'm a java guy coming over to Objective-C. In java, to add a variable to a string you'd have to do something along the lines of:

someString = "This string is equal to " + someNumber + ".";

I can't figure out how to do it in Objective-C though. I have an NSMutableString that I'd like to add to the middle of a string. How do I go about doing this?

I've tried:

NSString *someText = @"Lorem ipsum " + someMutableString;
NSString *someText = @"Lorem ipsum " + [someMutableString stringForm];

and a few other things, none of which seem to work. Also interchanged the +s with ,s.


回答1:


You can use appendString:, but in general, I prefer:

NSString *someText = [NSString stringWithFormat: @"Lorem ipsum %@", someMutableString];
NSString *someString = [NSString stringWithFormat: @"This is string is equal to %d.", someInt];
NSString *someOtherString = [NSString stringWithFormat: @"This is string is equal to %@.", someNSNumber];

or, alternatively:

NSString *someOtherString = [NSString stringWithFormat: @"This is string is equal to %d.", [someNSNumber intValue]];

etc...

These strings are autoreleased, so take care not to lose their value. If necessary, retain or copy them and release them yourself later.




回答2:


Try this:

NSMutableString * string1 = [[NSMutableString alloc] initWithString:@"this is my string"];

[string1 appendString:@" with more strings attached"];

//release when done
[string1 release];



回答3:


You need to use stringByAppendingString

NSString* string = [[NSString alloc] initWithString:@"some string"];
string = [string stringByAppendingString:@" Sweet!"];

Don't forget to [string release]; when your done of course.




回答4:


NSMutableString *string = [[NSMutableString alloc] init];

[string appendFormat:@"more text %@", object ];


来源:https://stackoverflow.com/questions/7070046/append-string-with-variable

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