我有一个像这样的长字符串:
je!tress:e?tu!tress:es?il!tress:e?nous!tress:ons?vous!tress:ez?ils!tress:ent?
我想在以后分割字符串:之前? 。所以我想进入数组:
{e,es,e,ons,ez,en}
我知道我可以这样做:
NSArray *subStrings = [stringToChange componentsSeparatedByString:@":"];
但还不够。 我怎么能这样做呢?任何帮助将不胜感激!
答案 0 :(得分:2)
另一种选择可能是使用NSRegularExpression类。
使用此模式:
\\:([^\?]+)\?
示例代码:
NSString *sample = @"je!tress:e?tu!tress:es?il!tress:e?nous!tress:ons?vous!tress:ez?ils!tress:ent?";
NSString *pattern = @"\\:([^\?]+)\?";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:&error];
NSArray *matches = [regex matchesInString:sample
options:0
range:NSMakeRange(0, [sample length])];
if(!error && [matches count] > 0) {
for (NSTextCheckingResult *match in matches) {
NSRange matchRange = [match range];
NSLog(@"%@" ,[sample substringWithRange:matchRange]);
}
}
输出:
2015-07-03 12:16:39.037 TestRegex[3479:48301] :e
2015-07-03 12:16:39.039 TestRegex[3479:48301] :es
2015-07-03 12:16:39.039 TestRegex[3479:48301] :e
2015-07-03 12:16:39.040 TestRegex[3479:48301] :ons
2015-07-03 12:16:39.040 TestRegex[3479:48301] :ez
2015-07-03 12:16:39.040 TestRegex[3479:48301] :ent
答案 1 :(得分:1)
使用NSScanner
解析字符串,搜索:
和?
标记。您可以丢弃您不想要的文本并捕获您所做的部分(根据您找到的标记)并将它们添加到数组中。
答案 2 :(得分:1)
试试这个,
NSString *names = @"je!tress:e?tu!tress:es?il!tress:e?nous!tress:ons?vous!tress:ez?ils!tress:ent?";
NSArray *namesarray = [names componentsSeparatedByString:@":"];
NSMutableArray *desiredArray = [[NSMutableArray alloc] initWithCapacity:0];
[namesarray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSRange rangeofsign = [(NSString*)obj rangeOfString:@"?"];
NSString *extractedName = [(NSString*)obj substringToIndex:rangeofsign.location];
[desiredArray addObject:extractedName];
}];
NSLog(@"%@",desiredArray);
答案 3 :(得分:1)
为简单起见,您可以尝试以下代码:
NSString *string = @"je!tress:e?tu!tress:es?il!tress:e?nous!tress:ons?vous!tress:ez?ils!tress:ent?";
NSArray *firstArray = [string componentsSeparatedByString:@":"];
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
for (NSString *newString in firstArray) {
NSArray *tempArray = [newString componentsSeparatedByString:@"?"];
if ([tempArray count] > 1) {
[finalArray addObject:[tempArray firstObject]];
}
}
NSLog(@"%@",finalArray);