当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - How do I easily separate a set of strings stored in a larger NSString?

问题描述:

I had a UILabel with the following text:

Medium, Black

What I intended to do was grab the words in the string and insert each into a mutable array so I could use each title later on to identify something.

With the help of Stackoverflow I done it like this:

NSMutableArray *chosenOptions = [[[[cell tapToEditLabel] text] componentsSeparatedByCharactersInSet:

[NSCharacterSet characterSetWithCharactersInString:@" ,"]] mutableCopy];

[chosenOptions removeObject:@""];

Now I can access this objects and they return the correct strings:

NSString *size = [chosenOptions objectAtIndex:0]; //Medium

NSString *colour = [chosenOptions objectAtIndex:1]; //Black

This is fine. But the problem starts when dealing with female sizes instead of males which are displayed like this:

[8 UK], [10 UK], [12 UK], [14 UK]

Let us say I now have a UILabel with the following text:

[8 UK], Black

Using the same code above my NSLog here:

NSLog(@"size label-> %@", size);

NSLog(@"colour label-> %@", colour);

Reads back:

size label-> [8

colour label-> UK]

Would appreciate a simple solution in code please.

The code that does the stripping doesn't take into account the way my female sizes are set in a string. I need a solution that will work with both male and female size string styles.

Thanks for your time.

网友答案:

Simply use componentsSeparatedByString:@", ".

NSArray *chosenOptions = [[[cell tapToEditLabel] text] componentsSeparatedByString:@", "];
网友答案:

Another way to do this that works with trailing commas with or without whitespace.

NSString *tag = @"Medium, Black";
NSMutableArray *options = [[tag componentsSeparatedByString:@","] mutableCopy];
NSString *size = [[options objectAtIndex:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *color = [[options objectAtIndex:1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(@"%@:%@", size, color);

We first split by just , and then remove all extra whitespace.

Here is some sample data:

NSArray *tags = @[@"[8 UK], Black", @"Medium, Black", @"Large, Red, ", @"Small, Black,"];
for (NSString *tag in tags) {
    NSMutableArray *options = [[tag componentsSeparatedByString:@","] mutableCopy];
    NSString *size = [[options objectAtIndex:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *color = [[options objectAtIndex:1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSLog(@"%@:%@", size, color);
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: