检查目标c中的字符串是否为回文结构

时间:2013-07-30 12:09:30

标签: objective-c

我正在尝试使用目标c检查字符串是否是回文结构。我是新手编程,没有其他编程语言的经验,所以请耐心等待。我陷入了我的if条件我想要它说如果字符串中的第一个位置等于最后一个字符串是回文。

我做错了什么?

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

10 个答案:

答案 0 :(得分:4)

除了不平衡的大括号外,从NSString访问字符比使用数组表示法更复杂。你需要使用方法characterAtIndex:你可以通过在不存在回文的情况下突破循环并在for循环之外进行长度调用来优化代码。

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方法将字符串全部设为小写。

正如Nikolai在评论中指出的那样,这只适用于包含“普通”unicode字符的字符串,这通常不正确 - 例如在将UTF8用于外语时。如果有可能,请使用以下代码,它会检查组合字符序列而不是单个字符。

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

答案 1 :(得分:4)

您尝试将NSString用作NSArray(或者可能像C字符串一样),这将无效。相反,您需要使用NSString方法characterAtIndex:来获取要测试的角色。

答案 2 :(得分:2)

var str: NSString = "123321"
var length = str.length
var isPalindrome = true

for index in 0...length/2{
    if(str.characterAtIndex(index) != str.characterAtIndex(length-1 - index)){
        print("\(index )not palindrome")
        isPalindrome = false
        break
    }
}

print("is palindrome: \(isPalindrome)")

答案 3 :(得分:1)

因为似乎还没有正确处理组合字符序列的答案我正在加上我的两分钱:

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

这会将字符串拆分为逻辑字符数组(普通用户称之为“字符”的字符串元素)。

答案 4 :(得分:1)

<强>递归

SELECT * FROM dbo.MyReportFunction(...)

非递归

- (BOOL)isPaliRec:(NSString*)str :(int)start :(int)end{
    if(start >= end)
       return YES;
    else if([str characterAtIndex:start] != [str characterAtIndex:end])
       return NO;
    else
       return [self isPaliRec:str :++start :--end];
}

您可以致电:

- (BOOL)isPali:(NSString*)str{
   for (int i=0; i<str.length/2; i++)
      if([str characterAtIndex:i] != [str characterAtIndex:(str.length-i-1)])
         return NO;

   return YES;
}

斯威夫特3:

NSString *str = @"arara";
[self isPaliRec:str :0 :(int)str.length-1];
[self isPali:str];

另外,你可以使用像// Recursive func isPaliRec(str: String, start: Int = 0, end: Int = str.characters.count-1) -> Bool { if start >= end { return true } else if str[str.index(str.startIndex, offsetBy: start)] != str[str.index(str.startIndex, offsetBy: end)] { return false } else { return isPaliRec(str: str, start: start+1, end: end-1) } } // Non Recursive func isPali(str: String) -> Bool { for i in 0..<str.characters.count/2 { let endIndex = str.characters.count-i-1 if str[str.index(str.startIndex, offsetBy: i)] != str[str.index(str.startIndex, offsetBy: endIndex)] { return false } } return true } // Using let str = "arara" isPaliRec(str: str) isPali(str: str) 这样的swift 3方法......它更优雅。 extension sample

答案 5 :(得分:1)

@import Foundation;

BOOL isPalindrome(NSString * str)
{
    if (!str || str.length == 0) return NO;
    if (str.length == 1) return YES;
    for(unsigned i = 0; i < str.length / 2; ++i)
        if ([str characterAtIndex:i] != [str characterAtIndex:str.length - i - 1]) return NO;
    return YES;
}

int main() {
    @autoreleasepool {
        NSLog(@"%s", isPalindrome(@"applelppa") ? "YES" : "NO");
    } return 0;
}

答案 6 :(得分:0)

 NSString *str=self.txtFld.text;
 int count=str.length-1;

    for (int i=0; i<count; i++) {
        char firstChar=[str characterAtIndex:i];
        char lastChar=[str characterAtIndex:count-i];
        NSLog(@"first=%c and last=%c",firstChar,lastChar);
        if (firstChar !=lastChar) {
            break;
        }
        else
            NSLog(@"Pailndrome");
    }

答案 7 :(得分:0)

We can also do this using NSRange like this...
enter code  NSString *fullname=@"123321";
NSRange rangeforFirst=NSMakeRange(0, 1);
NSRange rangeforlast=NSMakeRange(fullname.length-1, 1);
BOOL ispalindrome;
for (int i=0; i<fullname.length; i++) {
    if (![[fullname substringWithRange:rangeforFirst] isEqualToString:[fullname substringWithRange:rangeforlast]]) {
        NSLog(@"not match");
        ispalindrome=NO;
        return;
    }
    i++;
    rangeforFirst=NSMakeRange(i, 1);
    rangeforlast=NSMakeRange(fullname.length-i-1, 1);
}
NSLog(@"no is %@",(ispalindrome) ? @"matched" :@"not matched");

答案 8 :(得分:0)

NSString *str1 = @"racecar";
    NSMutableString *str2 = [[NSMutableString alloc] init];
    NSInteger strLength = [str1 length]-1;
    for (NSInteger i=strLength; i>=0; i--)
    {
       [str2 appendString:[NSString stringWithFormat:@"%C",[str1 characterAtIndex:i]]];

    }
 if ([str1 isEqual:str2])
        {
            NSLog(@"str %@ is palindrome",str1);
        }

答案 9 :(得分:0)

-(BOOL)checkPalindromeNumber:(int)number{
    int originalNumber,reversedNumber = 0,remainder;
    originalNumber=number;
    while (number!=0) {
        remainder=number%10;
        reversedNumber=(reversedNumber*10)+remainder;
        number=number/10;
    }

    if (reversedNumber==originalNumber) {
        NSLog(@"%d is Palindrome Number",originalNumber);

        return YES;
    }
    else{
        NSLog(@"%d is Not Palindrome Number",originalNumber);
        return NO;

    }
}