删除2个不同字符串中的常用字符

时间:2012-11-16 20:43:36

标签: iphone xcode nsstring uitextfield

我是Xcode和iPhone开发的新手。我遇到了问题。

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

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

1 个答案:

答案 0 :(得分: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++;
    }