Reputation: 121
I have a NSString
. This NSString
is split in different parts with ";"
.
I split this NSString
in 2 substrings (with [componentsSeparatedByString:@";"]
)
Now, I have a substring, with [componentsSeparatedByString:@";"]
, in a NSArray
.
In this substring I have (sometimes but not always !) a ","
.
When I have a ","
I want to spilt my substring in two "sub-substrings" and use this two sub-subtrings...
How can I do that ?
Thanks for your answers.
EDIT :
Hi @Alladinian, thanks for ur answer. That's a loop I need, I think. I want to add new contact to iPhone address book (First name and Last name) with QRCode.
My NSString
looks like :
NSString *_name = [NSString stringWithFormat:@"%@", code.contact];
My substring looks like:
NSArray *subStrings = [code.contact componentsSeparatedByString:@";"];
In my NSString
, I have (perhaps but not always) a ","
I need two different outputs : one for first name and one for last name.
I know how to add first name and last name separated by ","
but I don't know what to do if I have only a first name. Have only a first name crash my app...
For now, to skirt problem, I send Fist name and Last name in Fist name field... But it's not perfect for my sake.
Upvotes: 0
Views: 336
Reputation: 16032
Ok, here's some code you can use. You can't just use componentsSeparatedByString
for the name because there are 4 cases:
code:
NSString * mecardString = ...your string...
if ( [ mecardString hasPrefix:@"MECARD:" ] ) // is it really a card string? (starts with 'MECARD:')
{
mecardString = [ mecardString substringFromIndex:[ @"MECARD:" length ] ] ; // remove MECARD: from start
NSString * firstName = nil ;
NSString * lastName = nil ;
NSArray * components = [ mecardString componentsSeparatedByString:@";" ] ;
for( NSString * component in components ) // process all parts of MECARD string
{
NSString * lcString = [ component lowercaseString ] ;
if ( [ lcString hasPrefix:@"n:" ] )
{
// handle name ("N:")
NSRange commaRange = [ lcString rangeOfString:@"," ] ;
if ( commaRange.location == NSNotFound )
{
firstName = lcString ;
}
else
{
firstName = [ lcString substringFromIndex:NSMaxRange( commaRange ) ] ;
lastName = [ lcString substringToIndex:commaRange.location ] ;
}
NSCharacterSet * whitespaceCharSet = [ NSCharacterSet whitespaceAndNewlineCharacterSet ] ;
firstName = [ firstName stringByTrimmingCharactersInSet:whitespaceCharSet ] ;
lastName = [ firstName stringByTrimmingCharactersInSet:whitespaceCharSet ] ;
}
else if ( lcString hasPrefix:@"sound:" )
{
// handle name ("SOUND:")
}
// ... write code handle other parts of MECARD... (NICKNAME, BDAY, URL, etc)
else
{
// handle unknown case here
}
}
// you have names here
}
Upvotes: 1