Check if string is palindrome in objective c

前端 未结 10 2218
执念已碎
执念已碎 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:53

    As it seems there's no answer yet that handles composed character sequences correctly I'm adding my two cents:

    NSString *testString = @"\u00E0 a\u0300"; // "à à"
    
    NSMutableArray *logicalCharacters = [NSMutableArray array];
    [testString enumerateSubstringsInRange:(NSRange){0, [testString length]}
                                   options:NSStringEnumerationByComposedCharacterSequences
                                usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop)
    {
        [logicalCharacters addObject:substring];
    }];
    
    NSUInteger count = [logicalCharacters count];
    BOOL isPalindrome = YES;
    for (NSUInteger idx = 0; idx < count / 2; ++idx) {
        NSString *a = logicalCharacters[idx];
        NSString *b = logicalCharacters[count - idx - 1];
        if ([a localizedCaseInsensitiveCompare:b] != NSOrderedSame) {
            isPalindrome = NO;
            break;
        }
    }
    
    NSLog(@"isPalindrome: %d", isPalindrome);
    

    This splits the string into an array of logical characters (elements of a string that a normal user would call a "character").

提交回复
热议问题