如何在First Name
和Last Name
中分割全名。
NSString *fullName = @"John Luke Morite";
NSString *firstName = [[fullName componentsSeparatedByString:@" "] objectAtIndex:0]; //John
NSString *lastName = ?? // Luke Morite
答案 0 :(得分:6)
更好的方法:
NSString *fullName = @"John Luke Morite";
NSRange range = [fullName rangeOfString:@" "];
NSString *fname = [fullName substringToIndex:range.location];
NSString *lname = [fullName substringFromIndex:range.location+1];
答案 1 :(得分:3)
NSString *fullName = @"John Luke Morite";
NSString *firstName = [[string componentsSeparatedByString:@" "] objectAtIndex:0]; //John
NSString *lastName = [fullName substringFromIndex:[fullName rangeOfString:firstName].length + 1];
答案 2 :(得分:2)
这里的策略是寻找第一个空格,并采用剩余的字符
NSString *fullName = @"John Luke Morite";
NSRange range = [fullName rangeOfString:@" "];
NSString *lastName = [fullName substringFromIndex:range.length+1];
答案 3 :(得分:0)
您也可以使用split
来达到此目的:
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]) : ""