How do I add a space between two concatenated NSStrings?
-
21-08-2019 - |
Question
I have three string objects:
NSString *firstName;
NSString *lastName;
NSString *fullName;
The values for firstName
and lastName
are received from NSTextFields.
I then want to concatenate the two strings and place the result in fullname.
This is the code that I'm using:
fullName = [firstName stringByAppendingString:lastName];
However, the result does not put a space between the two names (e.g. JohnSmith).
How do I add in the space? I'd like the result to look like (John Smith).
Solution
The simplest way is this:
fullname = [[firstName stringByAppendingString:@" "] stringByAppendingString:lastName];
i.e. append the space, and then append the lastName.
OTHER TIPS
I'm amazed by the length of the other answers:
fullname = [NSString stringWithFormat:@"%@ %@", firstname, lastname];
fullName = [@[firstName, lastName]
componentsJoinedByString:@" "];
That is normal. You will have to add the space yourself.
(NSString*) description { return [[[NSString alloc]
initWithFormat:" %@ %@”,
firstname,
lastname] autorelease]; }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow