Objective-C NSString for loop with characterAtIndex

后端 未结 4 685
逝去的感伤
逝去的感伤 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, 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
    }
    

提交回复
热议问题