繁体   English   中英

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

[英]Check Objective-C String for specific characters

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

一种适合您的方法,远非唯一:

NString具有查找子字符串的方法,这些子字符串表示为位置和偏移量的NSRange ,由给定NSCharacterSet字符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

像这样使用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参数,您还必须查看文档以选择合适的参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM