2

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

4

3 回答 3

5

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

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并生成您的专门错误消息。

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

您可以将找到的无效字符累积到一个集合中(也许是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

高温高压

于 2013-10-13T17:57:22.743 回答
2

像这样使用 NSRegulareExpression。

NSString *str = @"your input string";
NSRegularExpression *regEx = [NSRegularExpression regularExpressionWithPattern:@"A|T|C|G" options:0 error:nil];
NSArray *matches = [regEx matchesInString:str options:0 range:NSMakeRange(0, str.length)];
for (NSTextCheckingResult *result in matches) {
    NSLog(@"%@", [str substringWithRange:result.range]);
}

此外,对于 options 参数,您必须查看文档以选择适合的参数。

于 2013-10-13T17:42:35.993 回答
0

查看 NSRegularExpression 类参考。

访问:https ://developer.apple.com/library/mac/documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html

于 2013-10-13T17:34:12.940 回答