The Human Bagel
The Human Bagel

Reputation: 7224

Pull first name and last initial from string

I have an NSString that contains a users full name. Some names are in the standard first and last formation (Kyle Begeman) and others are just a single name (TechCrunch).

How would I grab the first name as is and then the first initial of the last name, and if there is only one name, just grab the whole name?

Basically I want the above to be turned into Kyle B. or just TechCrunch depending on the name.

NSString *username = @"Kyle Begeman"
NSString *otherUserName = @"TechCrunch"

converted to 

@"Kyle B" 

// No conversion because it is a single word name
@"TechCrunch" 

Using substringToIndex is how I can grab the first letter in the whole string, and I know there is a way to separate the string by @" " whitespace into an array but I can figure out how to easily produce the result the way it needs to be.

Any help would be great!

Upvotes: 0

Views: 1290

Answers (3)

nikw
nikw

Reputation: 71

You could use NSScanner to find substrings.

NSString *name = @"Some name";
NSString *firstName;
NSString *lastName;
NSScanner *scanner = [NSScanner scannerWithString:name];
[scanner scanUpToString:@" " intoString:&firstName]; // Scan all characters up to the first space
[scanner scanUpToString:@"" intoString:&lastName]; // Scan remaining characters

if (lastName != nil) {
    // It was no space and lastName is empty
} else {
    // There was at least one space and lastName contains a string
}

Upvotes: 0

james00794
james00794

Reputation: 1147

(NSString*)firstNameWithInitial:(NSString*)userName {

    NSArray *array = [userName componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    array = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != ''"]];
    NSString *firstName = [array objectAtIndex:0];

    NSString finalNameString;
    if ([array count] > 1) {
        NSString *lastNameInitial = [[array objectAtIndex:1] substringToIndex:1];
        finalNameString = [firstName stringByAppendingString:[NSString stringWithFormat:@" %@", lastNameInitial]];
    else {
        finalNameString = firstName;
    }

    return finalNameString;
}

This function should return what you need. Note that you can modify this to work with people who have more than 2 names, by checking the number of objects in the array.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Find a position pos of the first space in the string. If there is no space, or if the space is the last character of the string, then return the entire string; otherwise, return substring in the range from zero to pos+1, inclusive:

NSRange range = [str rangeOfString:@" "];
if (range.location == NSNotFound || range.location == str.length-1) {
    return str;
} else {
    return [str substringToIndex:range.location+1];
}

Upvotes: 2

Related Questions