具有characterAtIndex的循环的Objective-C NSString

具有characterAtIndex的循环的Objective-C NSString,objective-c,xcode,loops,for-loop,Objective C,Xcode,Loops,For Loop,我试图一个字符一个字符地循环NSString,但遇到了EXC\u BAD\u访问错误。你知道怎么做吗?我已经在谷歌上搜索了好几个小时了,但还是搞不懂 这是我的代码(.m): self.textLength=[self.text length]; 对于(int position=0;position

我试图一个字符一个字符地循环NSString,但遇到了EXC\u BAD\u访问错误。你知道怎么做吗?我已经在谷歌上搜索了好几个小时了,但还是搞不懂

这是我的代码(.m):

self.textLength=[self.text length];
对于(int position=0;position

非常感谢

characterAtIndex:
返回一个
unichar
,因此您应该使用
NSLog(@“%C”),而不是
@“%@

您也不能对
unichar
使用
IsequalString
,只需使用
=='。
就可以了

如果要查找所有“.”的位置,可以使用
rangeOfString
。参考:


字符不是对象
characterAtIndex
返回
unichar
,它实际上是一个整数类型
无符号短字符
。您需要在
NSLog
中使用
%C
而不是
%@
。此外,字符不是
NSString
,因此无法发送
IsequalString
。您需要使用
ch=='.
ch
'.
进行比较

unichar ch = [self.text characterAtIndex:position];
NSLog(@"%C", ch);

if (ch == '.') {} // single quotes around dot, not double quotes
请注意,
'a'
是字符,
“a”
是C字符串,
@“a”
是NSString。它们都是不同类型的


当您在
NSLog
中对unichar
ch
使用
%@
时,它试图从内存位置
ch
打印一个无效的对象。因此,您将获得一个EXC\u BAD\u访问。

characterAtIndex:
返回一个
unichar
,声明为
typedef unsigned short unichar
调用
NSLog
时使用的格式说明符不正确,您可以执行
NSLog(@“%u”,[self.text characterAtIndex:position])
NSLog(@“%C”,[self.text characterAtIndex:position])如果要打印实际字符

此外,由于unichar的定义方式是这样的,因此它不是字符串,因此无法将其与其他字符串进行比较。尝试以下方法:

unichar textCharacter = '.';

if ([self.text characterAtPosition:position] == testCharacter) {
   // do stuff
}

如果要查找字符串中字符的位置,可以使用以下命令:

NSUInteger position = [text rangeOfString:@"."].location;
如果未找到字符或文本,您将获得NSNotFound:

if(position==NSNotFound)
    NSLog(@"text not found!");

您只是想找到字符串中某个特定字符的位置吗?如果是,有一个更简单的解决方案非常感谢您的解决方案,以及伟大的解释!太好了,谢谢!我正在使用
[nsstringwithformat:@“%hu”
,这也导致了一个错误。非常感谢您的回答!
if(position==NSNotFound)
    NSLog(@"text not found!");