美文网首页
iOS NSString字符串查找、截取、拆分、替换、验证、改变

iOS NSString字符串查找、截取、拆分、替换、验证、改变

作者: 关羽007 | 来源:发表于2019-03-05 15:42 被阅读0次

    NSString * string=@"2011-11-29 12-11-10";

    1查找

    NSRange range = [string rangeOfString:@"-"];

    if (range.location == NSNotFound)

    {

          NSLog(@"str中没有找到-");

    }else {

         NSLog(@"搜索范围%@",NSStringFromRange(range));

    }

    NSLiteralSearch区分大小写(完全比较)

    NSCaseInsensitiveSearch不区分大小写

    NSNumericSearch只比较字符串的个数,而不比较字符串的字面值

    从尾开始搜索:

    range = [str rangeOfString:@"456" options:NSBackwardsSearch] ;

    NSLog(@"从尾搜索的范围%@",NSStringFromRange(range));

    ios8.0以后使用,也是判断是否包含某个字符串:

    BOOL result = [@“123" containsString:@"2"];

    2替换

      string=[string stringByReplacingOccurrencesOfString:@"-"withString:@"/"];        

    NSLog(@"replaceStr=%@",string);

    3截取

    NSString*bStr = [string substringWithRange:NSMakeRange(loc,2)];

    loc表示从第几个字符开始,2表示截取两个字符;

    [str substringToIndex:n];

    从首字符开始截取n个字符;

    [string substringFromIndex:n];

    从第n+1位开始截取,至字符串最后;

    4拆分

    NSString*string =@"11111111A22222222";

    NSArray*array = [string componentsSeparatedByString:@"A"];//从字符A中分隔成2个元素的数组

    NSLog(@"array:%@",array);

    NSLog(@"array1 ==== %@",[array firstObject]);

    NSLog(@"array2 ==== %@",[array lastObject]);

    5.验证

    NSString*str1 =@"http:www.baidu.com";

    BOOL a = [str1 hasPrefix:@"http"];//是否是以http开头

    BOOL b = [str1 hasSuffix:@"com"];//文件路径是否以com结尾

    NSLog(@"a ===== %d ,b ==== %d",a,b);

    6.改变字符串的大小写

    NSString* str2 =@"beiJING";

    NSString*da = [str2 uppercaseString];//转成大写

    NSString*xiao = [str2 lowercaseString];//转成小写

    NSString*shouDa = [str2 capitalizedString];//首字母大写,其余小写

    NSLog(@"\n大写==%@\n小写=== %@\n首字母大写其余小写=== %@",da,xiao,shouDa);

    7.编码,解码

    编码

    NSString*hStr =@"你好啊";

    NSString*hString = [hStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"hString === %@",hString);

    解码

    NSString*str3 =@"\u5982\u4f55\u8054\u7cfb\u5ba2\u670d\u4eba\u5458\uff1f";

    NSString*str5 = [str3stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"string ==== %@",str5);

    相关文章

      网友评论

          本文标题:iOS NSString字符串查找、截取、拆分、替换、验证、改变

          本文链接:https://www.haomeiwen.com/subject/fghouqtx.html