How to connect string "Hello" and string "World" to "HelloWorld"? Looks like "+" doesn't work.
+7
A:
NSString *string = [NSString stringWithFormat:@"%@%@", @"Hello", @"World"];
NSLog(@"%@", string);
That should do the trick, although I am sure there is a better way to do this, just out of memory. I also must say this is untested so forgive me. Best thing is to find the stringWithFormat documentation for NSString.
Garrett
2009-02-26 06:44:27
You’re just missing @s on the Hello and World strings, otherwise this should work fine. There is also a message stringByAppendingString in NSString.
zoul
2009-02-26 06:57:07
This is exactly what I do, but as zoul said, prefix the strings with @ (ie @"hello")
Daniel H
2009-02-26 07:02:10
Yeah, NSString *string = [NSString stringWithFormat:@"%@%@", @"Hello", @"World"]; is also correct.
iPhoney
2009-02-26 13:28:13
If you plan on releasing the NSString, you should do an alloc and an initWithFormat. NSString *string = [[NSString alloc] initWithFormat:@"%@ %@", @"Hello", @"World"];
jocull
2010-09-16 19:34:08
+11
A:
How about:
NSString *hello = @"Hello";
NSString *world = @"World";
NSString *helloWorld = [hello stringByAppendingString:world];
b3b0p
2009-02-26 07:29:33
+3
A:
If you have two literal strings, you can simply code:
NSString * myString = @"Hello" @"World";
This is a useful technique to break up long literal strings within your code.
However, this will not work with string variables, where you'd want to use stringWithFormat: or stringByAppendingString:, as mentioned in the other responses.
Bill Heyman
2009-02-26 14:03:02
+1
A:
there's always NSMutableString..
NSMutableString *myString = [NSMutableString stringWithString:@"Hello"];
[myString appendString: @"World"];
Note:
NSMutableString *myString = @"Hello"; // won't work, literal strings aren't mutable
DaveJustDave
2009-03-18 18:14:38
You can not create a mutable string by assigning a literal string directly to the variable. You must do `NSMutableString *myString = [NSMutableString stringWithString:@"Hello"];` to create the mutable string.
Lawrence Johnston
2010-02-10 02:31:37
A:
Bill, I like yout simple solution and I'd like to note that you can also eliminate the space between the two NSStrings:
NSString * myString = @"Hello"@"World";
Ricardo
2010-06-12 17:08:04