Using Ipho开发者_JAVA技巧ne sdk 4.3 if i have an NSString like this
name@domain.com
How do i strip everything after the '@' so i am just left with 'name'.
Thanks
Split the string;
NSArray *parts= [emailAddress componentsSeparatedByString: @"@"];
and use the first part of the resultant array.
First use the - (NSRange)rangeOfString:(NSString *)aString - Function of the NSString Object to get the Position of the @-Charakter.
Then use - (NSString *)substringWithRange:(NSRange)aRange. aRange needs two Arguments first one is starting Element and the number of following Elements, so the first Argument is 0 and the second is the Position of the @. ;-)
tech74's answer is good. :)
Though I also have one approach on this one.
NSString *emailAddress = @"name@domain.com";
NSString *name = [emailAddress substringToIndex:[emailAddress rangeOfString:@"@"].location];
//to check:
NSLog(@"Name: %@", name);
Hope this is okay. If you will have a good use of the "domain" part, tech74's answer is a good approach.
NSString *emailAddress = @"name@Domain.com";
NSString *name = [emailAddress substringToIndex:[emailAddress rangeOfString:@"@"].location];
NSString *doman = [emailAddress substringFromIndex:[emailAddress rangeOfString:@"@"].location+1];
NSLog(@"Name: %@", name);
NSLog(@"Doman: %@", [doman lowercaseString]);
Output
Name: name
doman: domain.com
In case you need to restrict all upper case for domain
精彩评论