iOS 判断字符串中含有某个字符串 rangeOfString

复制代码
//判断roadTitleLab.text 是否含有qingjoin
            if([roadTitleLab.text rangeOfString:@"qingjoin"].location !=NSNotFound)//_roaldSearchText
            {
                NSLog(@"yes");
            }
            else 
            {
                NSLog(@"no");
            }


在iOS8以后,还可以用下面的方法来判断是否包含某字符串:

NSString *women = @"Hey  you are bitch ?";

if ([women containsString:@"bitch"]) {

NSLog(@"women 包含 bitch");

} else {

NSLog(@"women 不存在 bitch");

}

 

 

NSString *string = @"hello,fucking,you,bitch";

//字条串是否包含有某字符串

if ([string rangeOfString:@"fucking"].location == NSNotFound) {

NSLog(@"string 不存在 fucking");

} else {

NSLog(@"string 包含 fucking");

}

//字条串开始包含有某字符串

if ([string hasPrefix:@"hello"]) {

NSLog(@"string 包含 hello");

} else {

NSLog(@"string 不存在 hello");

}

//字符串末尾有某字符串;

if ([string hasSuffix:@"bitch"]) {

NSLog(@"string 包含 bitch");

} else {

NSLog(@"string 不存在 bitch");

}

 

 
复制代码

援引:https://www.cnblogs.com/qingjoin/archive/2012/12/14/2817690.html

附加:1和2

1删除过滤特殊字符

//    NSString *str_a = [targetString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"."]];

 

遇到一个需求需要过滤用户通讯录中的特殊字符串,研究了一下iOS的特殊字符串过滤方法。
首先定义一个NSCharacterSet,用来保存需要过滤的字符:

NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]|\n|\r|\t"];

 

然后首先找到了stringByTrimmingCharactersInSet方法:

NSString *trimmedString = [string stringByTrimmingCharactersInSet:set];

2.替换字符

  NSString *str_a = [targetString stringByReplacingOccurrencesOfString:@"." withString:@""];

 

trimmedString就是过滤后的字符串,但是发现stringByTrimmingCharactersInSet方法只能过滤字符串收尾两端的特殊字符串,字符串中间的特殊字符无法过滤。
然后询问了安卓同学的实现方法,是把特殊字符替换为空字符串。随后我在iOS中也找到了类似的方法。


NSString *newname = [[name componentsSeparatedByCharactersInSet:set] componentsJoinedByString:@""];
 

 

大工告成,完美去除字符串中的特殊字符!

另外还有一种方法就是一个一个字符串进行替换
使用stringByReplacingOccurrencesOfString这个方法将字符串里的非法字符逐个替代
具体代码如下:

hmutStr = [tempString stringByReplacingOccurrencesOfString:@" " withString:@""];
hmutStr = [tempString stringByReplacingOccurrencesOfString:@"#" withString:@""];
hmutStr = [tempString stringByReplacingOccurrencesOfString:@"*" withString:@""];
hmutStr = [tempString stringByReplacingOccurrencesOfString:@"+" withString:@""];
hmutStr = [tempString stringByReplacingOccurrencesOfString:@"-" withString:@""];

 

 

posted on   高彰  阅读(35942)  评论(0编辑  收藏  举报

编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· Windows 提权-UAC 绕过
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示