1

我是 Xcode 和 iPhone 开发的新手。我陷入了一个问题。

我有两个文本字段,我想比较这些字符串。如果有任何常见字符,则应将其省略/删除,并将新字符串显示在另一个文本字段中。

公共字符可以在字符串中的任何位置,并且一次只能省略一个字符(在 for 循环中)。

4

1 回答 1

1

我刚写了这个!我还没有发现它不起作用的情况!告诉我它是否适合你!

 NSMutableString *shortString; //put your shortest string in here
    NSMutableString *longString; //put your longest string in here

    //index for characters to be removed in short string
    int characterIndexesShort[shortString.length], characterIndexesLong[longString.length];
    int commonCharactersShort = 0, commonCharactersLong = 0;
    int cut = 0;

    for(int i = 0; i < shortString.length; i++)
    {
        int oldLongCharCount = commonCharactersLong;
        char currentLetter = [shortString characterAtIndex:i];

        for(int j = 0; j < longString.length; j++)
        {
            if(currentLetter  == [longString characterAtIndex:j])
                characterIndexesLong[commonCharactersLong++] = j;
        }

        if(commonCharactersLong != oldLongCharCount)
            characterIndexesShort[commonCharactersShort++] = i;
    }
    //At this point you will have arrays containing the indexes of the common characters in both strings


    for(int i = 0; i < commonCharactersLong; i++)
    {
        NSRange range;
        range.location = characterIndexesLong[i];
        range.length = 1;
        [longString replaceCharactersInRange:range withString:@""];
    }

    for(int i = 0; i < commonCharactersShort; i++)
    {
        NSRange range;
        range.location = characterIndexesShort[i] - cut;
        range.length = 1;
        [shortString replaceCharactersInRange:range withString:@""];
        cut++;
    }
于 2012-11-17T02:02:21.503 回答