【问题标题】:Deleting common characters in 2 different strings删除 2 个不同字符串中的常见字符
【发布时间】:2012-11-16 20:43:35
【问题描述】:

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

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

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

【问题讨论】:

  • 一定要保持两个字符串的顺序吗?
  • 请更好地定义常用字符?例如,它只需要在字符串中,还是在两个字符串中的相同位置。以abcdefggfedcba 为例。如果它只需要包含相同的字符,那么字符串将为空白。但如果它需要在同一个位置,那么在去除常见字符后,字符串将是d
  • 普通字符可以在字符串中的任何位置,但一次必须省略一个字符(在for循环中)

标签: iphone xcode nsstring uitextfield


【解决方案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++;
    }

【讨论】:

  • 也许可以用这个方法创建一个以 2 个字符串作为参数的方法。然后在开始时检查哪个是最长的,哪个是最短的,并将它们存储在相应的可变字符串中。
  • 感谢您的代码。如果两个字符串相等,那么?为什么这段代码适用于短字符串和长字符串?
  • 如果较长的字符串在 shortString 中它不起作用,因为您注意到底部的 for 循环略有不同。如果它们相等,则它可以以任何一种方式工作。如果你喜欢我的回答,请接受,如果你接受答案,堆栈溢出的人会更愿意帮助你。
  • 我现在正在处理它,我认为问题不在于实际字符串的长度,而在于它们在两个底部 for 循环中有多少匹配项。这就是编程的全部意义所在,这个想法只适用于你第一次编写它时的特定情况,然后经过一点调试和修改,它就可以工作了!
  • 没错。长度不是问题它的重复字符。例如 usmaan 和 ali 是两个字符串,如果我显示第二个字符串,我只得到“i”前两个被删除
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-27
  • 2022-11-23
  • 1970-01-01
  • 2023-04-09
  • 2011-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多