Reputation: 2600
How can I split a full name in First Name
and Last Name
.
NSString *fullName = @"John Luke Morite";
NSString *firstName = [[fullName componentsSeparatedByString:@" "] objectAtIndex:0]; //John
NSString *lastName = ?? // Luke Morite
Upvotes: 3
Views: 2316
Reputation: 2799
All of the codes in the other answers will crash in different situations. My approach is Messy but works without crashes (Objective-C):
NSString *fullName = @"Mehdi Mousavi Bakhtiari";
NSString *firstName = @"";
NSString *lastName = @"";
if (fullName != nil && fullName.length > 0) {
NSArray<NSString *> *parts = [fullName componentsSeparatedByString:@" "];
if (parts != nil && parts.count > 0) {
firstName = [parts objectAtIndex:0];
if (parts.count > 1)
for (int i = 1; i < parts.count; i++) {
lastName = [NSString stringWithFormat:@"%@ %@", lastName, (NSString *)[parts objectAtIndex:i]];
}
}
}
if (lastName != nil && lastName.length > 0)
lastName = [lastName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(@"first name: %@", firstName);
NSLog(@"middle name and last name: %@", lastName);
Upvotes: 0
Reputation: 1475
You can also use split
to acheive this:
let text = "Stack Overflow Z"
var fullNameArr = text.split(separator: " ", maxSplits: 1, omittingEmptySubsequences: true)
let firstName: String = String(fullNameArr.first ?? "")
let lastName: String = fullNameArr.count > 0 ? String(fullNameArr[1]) : ""
Upvotes: 0
Reputation: 5064
A better way:
NSString *fullName = @"John Luke Morite";
NSRange range = [fullName rangeOfString:@" "];
NSString *fname = [fullName substringToIndex:range.location];
NSString *lname = [fullName substringFromIndex:range.location+1];
Upvotes: 6
Reputation: 8180
Here the strategy is looking for the first space, and taking remaining characters
NSString *fullName = @"John Luke Morite";
NSRange range = [fullName rangeOfString:@" "];
NSString *lastName = [fullName substringFromIndex:range.length+1];
Upvotes: 2
Reputation: 21808
NSString *fullName = @"John Luke Morite";
NSString *firstName = [[string componentsSeparatedByString:@" "] objectAtIndex:0]; //John
NSString *lastName = [fullName substringFromIndex:[fullName rangeOfString:firstName].length + 1];
Upvotes: 4