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

时间:2013-10-13 17:27:06

标签: ios objective-c xcode5 illegal-characters

对于我正在处理的应用,我需要检查文本字段是否只包含字母A,T,C或G.此外,我想为任何其他输入字符制作专门的错误消息。 ex)“不要放入空间。”或“字母b不是可接受的值。”我已经阅读了其他几个这样的帖子,但它们是字母数字,我只想要指定的字符。

3 个答案:

答案 0 :(得分:4)

一种方法,远非独一无二:

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

等。 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

HTH

答案 1 :(得分: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参数,您必须查看文档以选择适合的选项。

答案 2 :(得分:0)