0

比較する必要がある文字列にランダムなデータ (名前) があります。データ (名前) は常に同じとは限りませんが、この形式になります。

たとえば、次のような NSString が 2 つあります。

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

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

これら 2 つの文字列に基づいて、両方の文字列にMike|が含まれていることがわかります。テイラー | ゴードン

したがって、これら 2 つの文字列間の同じデータの数は 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 に答える