Objective-C NSString for loop with characterAtIndex

后端 未结 4 687
逝去的感伤
逝去的感伤 2021-02-04 16:46

I\'m trying to loop through a NSString, character by character, but I\'m getting a EXC_BAD_ACCESS error. Do you have an idea how to do this right? I\'ve been googling for hours

相关标签:
4条回答
  • 2021-02-04 17:28

    characterAtIndex: returns a unichar, so you should use NSLog(@"%C", ...) instead of @"%@".

    You also cannot use isEqualToString for a unichar, just use == '.' is fine.

    If you want to find the position of all '.'s, you can use rangeOfString. Refer to:

    • String Programming Guide: Searching, Comparing, and Sorting Strings
    • Position of a character in a NSString or NSMutableString
    0 讨论(0)
  • 2021-02-04 17:28

    characterAtIndex: returns a unichar, which is declared as typedef unsigned short unichar; The format specifier you are using in your calls to NSLog are incorrect, you could just do NSLog(@"%u",[self.text characterAtIndex:position]); or NSLog(@"%C",[self.text characterAtIndex:position]); if you want the actual character to print out.

    Also, as a result of unichar being defined the way that it is, it's not a string, so you cannot compare it to other strings. Try something like:

    unichar textCharacter = '.';
    
    if ([self.text characterAtPosition:position] == testCharacter) {
       // do stuff
    }
    
    0 讨论(0)
  • 2021-02-04 17:28

    If you want to find the location of a character in a string you can use this:

    NSUInteger position = [text rangeOfString:@"."].location;
    

    if the character or text is not found you will get a NSNotFound:

    if(position==NSNotFound)
        NSLog(@"text not found!");
    
    0 讨论(0)
  • 2021-02-04 17:33

    Characters are not object. characterAtIndex returns unichar, which is actually an integer type unsigned short. You need to use %C instead of %@ in NSLog. Also character is not a NSString, so you can't send it isEqualToString. You need to use ch == '.' to compare ch against '.'.

    unichar ch = [self.text characterAtIndex:position];
    NSLog(@"%C", ch);
    
    if (ch == '.') {} // single quotes around dot, not double quotes
    

    Note that, 'a' is character, "a" is C string and @"a" is NSString. They all are different types.

    When you are using %@ with unichar ch in NSLog, it is trying to print an object from memory location ch which is invalid. Thus you are getting a EXC_BAD_ACCESS.

    0 讨论(0)
提交回复
热议问题