0

我需要比较的字符串中有随机数据(名称)。数据(名称)并不总是相同的,但会采用这种格式。

例如,我有两个这样的 NSString:

NSString *string1= @"Jordan Mike Liam Taylor Jill Gordon Phil Mark";

NSString *string2= @"Marcus Tony Taylor Anny Keenan Brittany Gordon Mike";

基于这两个字符串,我们可以看到两个字符串都包含Mike| 泰勒 | 戈登

所以这两个字符串之间的相同数据的计数是 3。但是我无法通过代码让它工作。以下是我迄今为止所拥有的。我觉得我很接近但并不完全在那里,并且非常感谢社区的一些帮助。先感谢您!

NSMutableArray *tempArray= [[NSMutableArray alloc] init];
[tempArray addObject:string1];
[tempArray addObject:string2];

NSCountedSet *bag = [[NSCountedSet alloc] initWithArray:tempArray];

NSString *mostOccurring;
NSUInteger highest = 0;
for (NSString *s in bag)
{
    if ([bag countForObject:s] > highest)
    {
        highest = [bag countForObject:s];
        mostOccurring = s;
    }
}
NSLog(@"Most frequent string: %d", highest);

编辑代码

NSUInteger highest = 1;
NSUInteger theCount=0;
for (NSString *s in bag)
{
    if ([bag countForObject:s] > highest)
    {
        highest = [bag countForObject:s];
        mostOccurring = s;

    }
if (highest ==2)
{
    theCount++;
}

}
NSLog(@"Most frequent string: %d", theCount);
4

2 回答 2

2

我迟到了回答这个问题,但请看这里:

NSString *string1= @"Jordan Mike Liam Taylor Jill Gordon Phil Mark a";
NSString *string2= @"Marcus Tony Taylor Anny Keenan Brittany Gordon Mike";
NSMutableSet *set1=[NSMutableSet setWithArray:[string1 componentsSeparatedByString:@" "]];
NSMutableSet *set2=[NSMutableSet setWithArray:[string2 componentsSeparatedByString:@" "]];
[set1 intersectSet:set2];

NSArray *intersect=[set1 allObjects];//intersect contains all the common elements

NSLog(@"Common count is  %ld.",[intersect count]);
于 2013-01-07T07:20:35.383 回答
1

你根本不需要改变你的代码示例来实现你想要的:

    NSString *string1= @"Jordan Mike Liam Taylor Jill Gordon Phil Mark";
    NSString *string2= @"Marcus Tony Taylor Anny Keenan Brittany Gordon Mike";

    NSMutableArray *tempArray= [[NSMutableArray alloc] init];
    [tempArray addObjectsFromArray:[string1 componentsSeparatedByString:@" "]];
    [tempArray addObjectsFromArray:[string2 componentsSeparatedByString:@" "]];

    NSCountedSet *bag = [[NSCountedSet alloc] initWithArray:tempArray];


    NSUInteger repeats = 0;
    NSMutableArray *matches = [[NSMutableArray alloc] init];
    for (NSString *s in bag)
    {
        if ([bag countForObject:s] > 1)
        {
            repeats++;
            [matches addObject:s];
        }
    }
    NSLog(@"Number of names repeated: %ld", repeats);
    NSLog(@"Matches: %@", matches);
于 2013-01-07T06:35:25.277 回答