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

Mac*_*541 2 objective-c illegal-characters ios xcode5

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

CRD*_*CRD 5

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

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

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

NSCharacterSet *ATCG = [NSCharacterSet characterSetWithCharactersInString:@"ATCG"];
Run Code Online (Sandbox Code Playgroud)

以及一组不应该做的事情:

NSCharacterSet *invalidChars = [ATCG invertedSet];
Run Code Online (Sandbox Code Playgroud)

您现在可以搜索包含以下内容的任意范围的字符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];
Run Code Online (Sandbox Code Playgroud)

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

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

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

您还可以使用正则表达式,请参阅NSRegularExpressions

等等HTH

附录

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

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
Run Code Online (Sandbox Code Playgroud)

华泰