【问题标题】:Objective-C NSString for loop with characterAtIndex带有 characterAtIndex 的 Objective-C NSString for 循环
【发布时间】:2012-04-25 12:17:43
【问题描述】:

我正在尝试逐个字符地循环遍历 NSString,但我遇到了 EXC_BAD_ACCESS 错误。您知道如何正确执行此操作吗?我已经在谷歌上搜索了几个小时,但无法弄清楚。

这是我的代码 (.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 .");
    }
}

非常感谢!

【问题讨论】:

  • 您是否只是想在字符串中查找特定字符的位置?如果是,有一个更简单的解决方案

标签: objective-c xcode loops for-loop


【解决方案1】:

字符不是对象。 characterAtIndex返回unichar,实际上是整数类型unsigned short。您需要在NSLog 中使用%C 而不是%@。另外字符不是NSString,所以你不能发送isEqualToString。您需要使用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_BAD_ACCESS。

【讨论】:

  • 非常感谢您的解决方案,以及出色的解释!
  • 太好了,谢谢!我使用的是[NSString stringWithFormat:@"%hu",这也导致了错误。
【解决方案2】:

characterAtIndex: 返回一个unichar,所以你应该使用NSLog(@"%C", ...) 而不是@"%@"

unichar 也不能使用isEqualToString,只需使用== '.' 即可。

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

【讨论】:

    【解决方案3】:

    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
    }
    

    【讨论】:

    • 非常感谢您的回答!
    【解决方案4】:

    如果你想在一个字符串中找到一个字符的位置,你可以使用这个:

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

    如果找不到字符或文本,您将获得 NSNotFound:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-28
      • 2020-11-04
      • 1970-01-01
      • 2011-03-20
      • 2013-09-29
      • 2013-10-08
      • 2015-11-05
      相关资源
      最近更新 更多