0

对于我的应用程序,我需要比较单词而不是整个单词。如果它在单词中的同一位置,我希望它重新识别一个字母。所有单词的最大长度为 6。

这两个词都显示在一个标签中。

标签1和标签2

例如,如果 label1 中的单词是“按钮”,我想将其拆分为 6 个字符串。

string1: B
string2: u
string3: t
string4: t 
string5: o
string6: n

然后对于我的 label2 是“砖块”,将其分成 6 份。

string7: B
string8: r
string9: i
string10: c 
string11: k
 string12: s

现在我可以比较字符串 1:string7 等。

这样我可以比较单词中的所有字符对吗?我的问题是,这是正确的做法吗?如果是这样,代码会是什么样子?

我希望有人知道我的意思并知道如何做到这一点!谢谢你

4

1 回答 1

0

我会做这样的事情:

- (void)findEqualsIn:(NSString *)string1 and:(NSString *)string2 {
    for (int i = 0; i < [string1 length] && i < [string2 length]; i++) {
        if ([string1 characterAtIndex:i] == [string2 characterAtIndex:i]) {
            NSLog(@"%c is at index %i of both strings", [string1 characterAtIndex:i], i);
        }
    }
}

我不知道你想用它做什么或你想如何返回信息(可能是一个 NSArray,其中包含所有匹配的索引?)

编辑

- (void)findEqualsIn:(NSString *)string1 and:(NSString *)string2 {
    NSMutableArray *string1chars = [[NSMutableArray alloc] init];
    NSMutableArray *string2chars = [[NSMutableArray alloc] init];

    //filling the string1chars array
    for (int i = 0; i < [string1 length]; i++) {
        [string1chars addObject:[NSString stringWithFormat:@"%c", [string1 characterAtIndex:i]]];
    }

    //filling the string2chars array
    for (int i = 0; i < [string2 length]; i++) {
        [string2chars addObject:[NSString stringWithFormat:@"%c", [string2 characterAtIndex:i]]];
    }

    //checking if they have some letters in common on the same spot
    for (int i = 0; i < [string1chars count] && i < [string2chars count]; i++) {
        if ([[string1chars objectAtIndex:i] isEqualToString:[string2chars objectAtIndex:i]]) {
            //change the color of the character at index i to green
        } else {
            //change the color of the character at index i to the standard color
        }
    }
}
于 2012-04-23T10:27:31.097 回答