Objective-C的NSString for循环与characterAtIndex [英] Objective-C NSString for loop with characterAtIndex
问题描述
我试图循环遍历一个字符的NSString,但是我得到一个EXC_BAD_ACCESS错误。你有一个想法如何做到这一点?我已经搜索了几个小时,但无法弄清楚。
这是我的代码(.m):
self.textLength = [self.text length];
(int position = 0; position< self.textLength; position ++){
NSLog(@%@,[self.text characterAtIndex:position]) ;
if([[self.text characterAtIndex:position] isEqualToString:@。]){
NSLog(@it's a。);
$ b $ p $非常感谢!
解决方案字符不是对象。 characterAtIndex
返回 unichar
,它实际上是一个整数类型 unsigned short
。您需要在 NSLog
中使用%C
,而不是%@
>。而且字符不是 NSString
,所以你不能发送 isEqualToString
。你需要使用 ch =='。'
来比较 ch
和'。'
。
unichar ch = [self.text characterAtIndex:position];
NSLog(@%C,ch);
if(ch =='。'){} //单引号,而不是双引号
请注意,'a'
是字符,a
是C字符串, @a
是NSString。它们都是不同的类型。
当您使用%@
with unichar ch
在 NSLog
中,它试图从内存位置 ch
打印一个无效的对象。因此你得到一个EXC_BAD_ACCESS。
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!
解决方案 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.
这篇关于Objective-C的NSString for循环与characterAtIndex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!