Check if string is palindrome in objective c

前端 未结 10 2214
执念已碎
执念已碎 2021-01-07 02:15

I\'m trying to check if a string is palindrome or not using objective c. I\'m new to programming without any experience in other programming languages so bear with me please

10条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-07 02:30

    Apart from the unbalanced braces, accessing a character from NSString is more complicated than using array notation. You need to use the method characterAtIndex: You can optimise your code, by breaking out of the loop if a palindrome is impossible and taking the length call outside of the for loop.

    NSString *p = @"121";
    
    NSInteger length = p.length;
    NSInteger halfLength = (length / 2);
    
    BOOL isPalindrome = YES;
    
    for (int i = 0; i < halfLength; i++) {
         if ([p characterAtIndex:i] != [p characterAtIndex:length - i - 1]) {
            isPalindrome = NO;
            break;
         }
    }
    

    It may be desirable to check case insensitively. To do this, make the string be all lowercase before looping, using the lowercaseString method.

    As pointed out by Nikolai in the comments, this would only work for strings containing 'normal' unicode characters, which is often not true — such as when using UTF8 for foreign languages. If this is a possibility, use the following code instead, which checks composed character sequences rather than individual characters.

    NSString *p = @"121";
    NSInteger length = p.length;
    
    NSInteger halfLength = length / 2;
    
    __block BOOL isPalindrome = YES;
    
    [p enumerateSubstringsInRange:NSMakeRange(0, halfLength) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         NSRange otherRange = [p rangeOfComposedCharacterSequenceAtIndex:length - enclosingRange.location - 1];
    
         if (![substring isEqualToString:[p substringWithRange:otherRange]]) {
             isPalindrome = NO;
             *stop = YES;
         }
    }];
    

提交回复
热议问题