检查字符串c是否在目标c中是回文 [英] Check if string is palindrome in objective c

查看:100
本文介绍了检查字符串c是否在目标c中是回文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查字符串是否是回文字符串或不使用目标c.我是编程新手,没有其他编程语言的经验,所以请多多包涵.如果遇到这种情况,我会陷入困境,我想说的是,如果字符串中的第一个位置等于最后一个位置,则该字符串是回文.

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. I get stuck at my if condition I want it to say that if the first position in the string is equal to the last one the string is a palindrome.

我在做什么错了?

int main (int argc, const char * argv[])
{
    NSString *p = @"121" ;   
    BOOL palindrome = TRUE;
    for (int i = 0 ; i<p.length/2+1 ; i++)
    {
         if (p[i] != p [p.Length - i - 1])
                    palindrome = false;
    }
    return (0);
}

推荐答案

除了不平衡的花括号外,从NSString访问字符比使用数组表示法更复杂.您需要使用方法characterAtIndex:.可以通过以下方法来优化代码:在不可能进行回文的情况下退出循环,并在for循环之外进行length调用.

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;
     }
}

可能希望不区分大小写地进行检查.为此,请使用lowercaseString方法在循环之前将字符串全部小写.

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

正如Nikolai在评论中指出的那样,这仅适用于包含普通" unicode字符的字符串,而这通常不是正确的-例如,对于外语使用UTF8.如果可能的话,请改用以下代码,该代码检查组成的字符序列而不是单个字符.

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;
     }
}];

这篇关于检查字符串c是否在目标c中是回文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆