ios 用变量追加字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7070046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append string with variable
提问by Peter Kazazes
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:
我是一个来到 Objective-C 的 Java 人。在 java 中,要将变量添加到字符串中,您必须执行以下操作:
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?
我不知道如何在 Objective-C 中做到这一点。我有一个NSMutableString
我想添加到字符串中间的。我该怎么做?
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.
和其他一些东西,似乎都不起作用。也将+
s 与,
s互换。
回答by Rudy Velthuis
You can use appendString:
, but in general, I prefer:
您可以使用appendString:
,但总的来说,我更喜欢:
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.
这些字符串是自动释放的,所以注意不要失去它们的价值。如有必要,保留或复制它们,稍后自己释放它们。
回答by Louie
Try this:
尝试这个:
NSMutableString * string1 = [[NSMutableString alloc] initWithString:@"this is my string"];
[string1 appendString:@" with more strings attached"];
//release when done
[string1 release];
回答by Trevor
You need to use stringByAppendingString
你需要使用 stringByAppendingString
NSString* string = [[NSString alloc] initWithString:@"some string"];
string = [string stringByAppendingString:@" Sweet!"];
Don't forget to [string release];
when your done of course.
[string release];
当然,当你完成时不要忘记。
回答by Jorge Martínez Mauricio
NSMutableString *string = [[NSMutableString alloc] init];
[string appendFormat:@"more text %@", object ];