【问题标题】:Empty character in Objective-CObjective-C 中的空字符
【发布时间】:2011-01-11 13:38:39
【问题描述】:

我正在创建一些代码来查找字符之间的空格,并使用空格之前和之后的字符。这些字符存储在一个 NSString 中。这是我到目前为止所拥有的,但是,它没有看到空字符。

    NSString *tempTitle = self.title;
unsigned int indexOfSpace; // Holds the index of the character with the space
unsigned int titleLength = (unsigned int)self.title.length; // Holds the length of the title
for (unsigned int count = 0; count < titleLength; count++)
{
    if ([tempTitle characterAtIndex:count] == "") // If the character at the index is blank, store this and stop
    {
        indexOfSpace == count;
    }
    else // Else, we keep on rollin'
    {
        NSLog(@"We're on character: %c", [tempTitle characterAtIndex:count]);
    }
}

我试过 nil ,空字符串 ("") 和 " " 但无济于事。有什么想法吗?

【问题讨论】:

  • indexOfSpace == count; 包含一个双等号。你的意思是它是一个等号吗?
  • 糟糕,我没有呵呵。谢谢!

标签: objective-c nsstring char for-loop spaces


【解决方案1】:

你的空格字符应该用单引号,而不是双引号。单引号为您提供 C 中的 char 类型。(双引号创建一个字符串文字,其本质上用作 char * 并且永远不会通过您的比较。)

-[NSString characterAtIndex:] 返回一个类型unichar,它是一个unsigned short,所以你应该能够直接将它与一个空格字符' ' 进行比较,如果你想要这样做的话。

请注意,nil 和空字符串在这里没有用——它们实际上都不是字符,而且无论如何你的字符串永远不会“包含”这些。

您还应该看到直接在字符串中查找字符的 NSString 方法,例如-[NSString rangeOfString:] 及其表兄弟。这会阻止您自己编写循环,尽管不幸的是这些在语法上有点冗长。

【讨论】:

  • 啊,这成功了!谢谢!我会研究 rangeOfString 方法,如果它像你说的那样冗长,我可能会保留我的方法,因为它正在工作。
  • 如果你不止一次这样做并且想要一个更简单的界面,你可以考虑向 NSString 添加一个“类别”(搜索这个),在一个透明的地方提供功能。
猜你喜欢
  • 2011-03-29
  • 1970-01-01
  • 1970-01-01
  • 2012-01-12
  • 1970-01-01
  • 1970-01-01
  • 2015-06-20
  • 1970-01-01
  • 2011-06-17
相关资源
最近更新 更多