简体   繁体   English

删除2个不同字符串中的公共字符

[英]Deleting common characters in 2 different strings

I am new to Xcode and iPhone developing. 我是Xcode和iPhone开发的新手。 I am stuck in a problem. 我陷入了一个问题。

I have two textFields and i want to compare these strings. 我有两个textFields,我想比较这些字符串。 If there is any common character then it should be omitted/deleted, and the new string is displayed in another textfield. 如果存在任何公共字符,则应将其省略/删除,新字符串将显示在另一个文本字段中。

The common character can be at any location in the string and only one character is omitted at a time(in for loop). 公共字符可以在字符串中的任何位置,并且一次只省略一个字符(在for循环中)。

I just wrote this! 我只是写了这个! I havent found cases where it doesnt work! 我还没有发现不起作用的情况! Tell me if it works for you! 告诉我它是否适合您!

 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++;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM