views:

1693

answers:

4

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).

+2  A: 

The simplest way is this:

fullname = [[firstName stringByAppendingString:@" "] stringByAppendingString:lastName];

i.e. append the space, and then append the lastName.

Alnitak
A: 

That is normal. You will have to add the space yourself.

(NSString*) description { return [[[NSString alloc] 
                          initWithFormat:" %@ %@”, 
                          firstname, 
                          lastname] autorelease]; }
dirkgently
A: 
fullName = [[NSArray arrayWithObjects:firstName, lastName, nil]
             componentsJoinedByString:@" "];
newacct
+2  A: 

I'm amazed by the length of the other answers:

fullname = [NSString stringWithFormat:@"%@ %@", firstname, lastname];
Sam V