Objective-C NSString for loop with characterAtIndex

23,189

Solution 1

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.

Solution 2

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:

Share:
23,189
Linus
Author by

Linus

Updated on July 09, 2022

Comments

  • Linus
    Linus almost 2 years

    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 now but can't figure it out.

    Here is my code (.m):

    self.textLength = [self.text length];
    
    for (int position=0; position < self.textLength; position++) {
    
        NSLog(@"%@", [self.text characterAtIndex:position]);
    
        if ([[self.text characterAtIndex:position] isEqualToString:@"."]){
            NSLog(@"it's a .");
        }
    }
    

    Thanks a lot!

  • Linus
    Linus about 12 years
    Thank you so much for the solution, as well as the great explanation!
  • Linus
    Linus about 12 years
    Thanks a lot for your answer!
  • Patrick
    Patrick over 11 years
    Great, thanks! I was using [NSString stringWithFormat:@"%hu" which also caused an error.