如何找出 NSString 中是否存在特定字符?

发布于 2024-12-21 11:21:45 字数 138 浏览 2 评论 0原文

我有两个名为 Country 和 searchtext 的 NSString。我需要检查该国家/地区是否包含搜索文本。

例如:country=Iceland,searchtext=c,这里单词iceland包含字符“c”。

谢谢。

I have two NSStrings named country and searchtext. I need to check whether the country contains the searchtext.

Eg: country = Iceland and searchtext = c, here the word iceland contains the character 'c'.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

晚风撩人 2024-12-28 11:21:45

试试这个:

NSRange range = [country rangeOfString:searchtext];
if (range.location != NSNotFound)
{
}

您的范围对象中还包含比赛的位置(地点)和长度(在本例中无趣,但在其他情况下可能很有趣)。请注意,searchtext 不得为nil。如果您只对匹配(而不是位置)感兴趣,您甚至可以将其压缩为

if ([country rangeOfString:searchtext].location != NSNotFound)
{
}

Try this:

NSRange range = [country rangeOfString:searchtext];
if (range.location != NSNotFound)
{
}

You also have the position (location) and length of your match (uninteresting in this case but might be interesting in others) in your range object. Note that searchtext must not be nil. If you are only interested in matching (and not the location) you can even condense this into

if ([country rangeOfString:searchtext].location != NSNotFound)
{
}
傻比既视感 2024-12-28 11:21:45
NSString *st =    @"Iceland";
NSString *t_st = @"c";      
NSRange rang =[st rangeOfString:t_st options:NSCaseInsensitiveSearch];

   if (rang.length == [t_st length]) 
   {
          NSLog(@"done");
   }
   else
   {
          NSLog(@"not done");
   }
NSString *st =    @"Iceland";
NSString *t_st = @"c";      
NSRange rang =[st rangeOfString:t_st options:NSCaseInsensitiveSearch];

   if (rang.length == [t_st length]) 
   {
          NSLog(@"done");
   }
   else
   {
          NSLog(@"not done");
   }
追风人 2024-12-28 11:21:45

很简单...试试这个

-(BOOL)doesString:(NSString *)string containCharacter:(char)character
{
    if ([string rangeOfString:[NSString stringWithFormat:@"%c",character]].location != NSNotFound)
    {
        return YES;
    }
    return NO;
}

Very simple... try this

-(BOOL)doesString:(NSString *)string containCharacter:(char)character
{
    if ([string rangeOfString:[NSString stringWithFormat:@"%c",character]].location != NSNotFound)
    {
        return YES;
    }
    return NO;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文