ios - 检查 Objective-C 字符串中的特定字符

标签 ios objective-c xcode5 illegal-characters

对于我正在开发的应用程序,我需要检查文本字段是否只包含字母 A、T、C 或 G。此外,我想为任何其他输入的字符制作专门的错误消息。例如)“不要放入空格。”或“字母 b 不是可接受的值。”我读过其他几篇类似的文章,但它们是字母数字的,我只想要指定的字符。

最佳答案

适合您的一种方法,远非独一无二:

NString 具有查找子字符串的方法,表示为位置和偏移量的 NSRange,由给定 NSCharacterSet 中的字符组成。

字符串中应包含的内容的集合:

NSCharacterSet *ATCG = [NSCharacterSet characterSetWithCharactersInString:@"ATCG"];

以及不应该做的事情的集合:

NSCharacterSet *invalidChars = [ATCG invertedSet];

您现在可以搜索由 invalidChars 组成的任意范围的字符:

NSString *target; // the string you wish to check
NSRange searchRange = NSMakeRange(0, target.length); // search the whole string
NSRange foundRange = [target rangeOfCharacterFromSet:invalidChars
                                             options:0 // look in docs for other possible values
                                               range:searchRange];

如果没有无效字符,则 foundRange.location 将等于 NSNotFound,否则您更改检查 foundRange 中的字符范围并生成您的专用错误消息。

您重复该过程,根据 foundRange 更新 searchRange,以查找所有无效字符的运行。

您可以将找到的无效字符累积到一个集合中(可能是 NSMutableSet)并在最后生成错误消息。

你也可以使用正则表达式,见NSRegularExpressions

等等。

附录

有一个非常简单的方法来解决这个问题,但我没有给出它,因为你给我的字母暗示我你可能正在处理非常长的字符串并且使用上面提供的方法可能是一个值得的胜利。但是,在您发表评论后再三考虑,也许我应该将其包括在内:

NSString *target; // the string you wish to check
NSUInteger length = target.length; // number of characters
BOOL foundInvalidCharacter = NO;   // set in the loop if there is an invalid char

for(NSUInteger ix = 0; ix < length; ix++)
{
   unichar nextChar = [target characterAtIndex:ix]; // get the next character

   switch (nextChar)
   {
      case 'A':
      case 'C':
      case 'G':
      case 'T':
         // character is valid - skip
         break;

      default:
         // character is invalid
         // produce error message, the character 'nextChar' at index 'ix' is invalid
         // record you've found an error
         foundInvalidCharacter = YES;
   }
}

// test foundInvalidCharacter and proceed based on it

HTH

关于ios - 检查 Objective-C 字符串中的特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19348104/

相关文章:

objective-c - 使基类调用子类中的方法

iphone - CGContextShowTextAtPoint 已弃用 - 我现在应该使用什么?

ios - Xcode 5 表示测试失败但显示绿色复选标记

ios - AUParameterTree dealloc导致死锁

ios - dyld : Library not loaded: @rpath/MapboxMobileEvents. 框架/MapboxMobileEvents

ios - 无法找到 ScrollView 属性以了解 ScrollView 滚动了多少像素

iphone - EKEventEditor 在 iPhone 上崩溃,但在 iPad 上没有

ios7 - 我需要知道如何删除选定的目标依赖项

ios - 如何向作为 UIViewController 子类的parentViewController 发送消息?

ios - 使用 performSelectorOnMainThread iOS 在调用中转换对象