2

我正在尝试检查字符串是否为回文或不使用目标 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);
}
4

10 回答 10

4

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;
     }
}];
于 2013-07-30T12:22:56.960 回答
4

You're trying to use an NSString as an NSArray (or probably, like a C string), which won't work. Instead, you need to use the NSString method characterAtIndex: to get the character to test.

于 2013-07-30T12:24:52.150 回答
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)")
于 2016-10-23T17:37:04.433 回答
1

递归的

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

您可以致电:

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

斯威夫特 3:

// 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 方法,例如string extension... 更优雅。扩展样本

于 2015-04-29T06:39:54.473 回答
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);

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

于 2013-07-30T14:13:33.183 回答
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;
}
于 2015-06-06T17:24:10.473 回答
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);
        }
于 2015-03-17T19:43:47.320 回答
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");
    }
于 2013-12-30T17:02:17.710 回答
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");
于 2014-05-20T09:41:16.947 回答
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;

    }
}
于 2017-05-13T13:06:29.397 回答