gpt4 book ai didi

objective-c - 奇怪的 cocoa 虫?

转载 作者:行者123 更新时间:2023-12-03 16:50:55 27 4
gpt4 key购买 nike

嘿伙计们,下面是我用于学校作业的一段代码。每当我输入一个带有 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 中的一些奇怪的错误吗?或者我错过了什么?

  • B

最佳答案

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

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

用途:

if(![charOne isEqualToString:charTwo]) {

而不是:

if(charOne != charTwo) {

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

关于objective-c - 奇怪的 cocoa 虫?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3804206/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com