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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8517760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:53:09  来源:igfitidea点击:

How to find out a specific character is present in a NSString or not?

iosxcodensstring

提问by Arun

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

我有两个名为 country 和 searchtext 的 NSStrings。我需要检查国家是否包含搜索文本。

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

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

Thanks.

谢谢。

回答by Dennis Bliefernicht

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 searchtextmust not be nil. If you are only interested in matching (and not the location) you can even condense this into

您还可以在范围对象中获得匹配的位置(位置)和长度(在这种情况下不感兴趣,但在其他情况下可能很有趣)。请注意,searchtext一定不能nil。如果您只对匹配(而不是位置)感兴趣,您甚至可以将其压缩为

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

回答by Sirji

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");
   }

回答by Rajesh Loganathan

Very simple... try this

很简单……试试这个

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