1

嘿伙计们,下面是我用于学校作业的一段代码。每当我输入一个带有 O 的单词(大写的 o)时,它就会失败!每当这个程序中有一个或多个大写 O 时,它会返回 false 并记录:句子不是回文。

回文,对于不知道回文是什么的人来说,是一个从左到右,从左到右读相同的词。(例如大声笑、皮划艇、复兴者等)我在尝试检查“最古老”的回文时发现了这个错误:SATOR AREPO TENET OPERA ROTAS。

当我将所有大写的 o 更改为小写的 o 时,它会起作用并返回 true。让我清楚地说明,这段代码所有带有大写 O 的句子/单词都返回 false。一个大写的 o 就足以使这个程序失败。

-(BOOL)testForPalindrome:(NSString *)s position:(NSInteger)pos {
    NSString *string = s;
    NSInteger position = pos;
    NSInteger stringLength = [string length];
    NSString *charOne = [string substringFromIndex:position];
    charOne = [charOne substringToIndex:1];

    NSString *charTwo = [string substringFromIndex:(stringLength - 1 - position)];
    charTwo = [charTwo substringToIndex:1];
    if(position > (stringLength / 2)) {
        NSString *printableString = [NSString stringWithFormat:@"De following word or sentence is a palindrome: \n\n%@", string];
        NSLog(@"%@ is a palindrome.", string);
        [textField setStringValue:printableString];
        return YES;
    }
    if(charOne != charTwo) {
        NSLog(@"%@, %@", charOne, charTwo);
        NSLog(@"%i", position);
        NSLog(@"%@ is not a palindrome.", string);
        return NO;
    }
    return [self testForPalindrome:string position:position+1]; 
}

那么,这是 Cocoa 中的一些奇怪的错误吗?还是我错过了什么?

4

2 回答 2

4

这当然不是 Cocoa 中的错误,正如您内心深处可能知道的那样。

您的比较方法导致了这个“Cocoa 中的错误”,您正在比较 charOne 和 charTwo 的地址。相反,您应该将字符串的内容与 isEqualToString 消息进行比较。

利用:

if(![charOne isEqualToString:charTwo]) {

代替:

if(charOne != charTwo) {

编辑:在测试项目中对其进行了测试,可以确认这是问题所在。

于 2010-09-27T13:45:01.130 回答
3

不要使用charOne != charTwo

而是使用其中一种NSString 比较方法。

if ([charOne caseInsensitiveCompare:charTwo] != NSOrderedSame)

它也可能与本地化有关(但我对此表示怀疑)。

于 2010-09-27T13:47:05.337 回答