NSString 字符串的一些操作

       在对字符串进行使用的时候,有些字符串我们需要删除或者替换一些我们不需要的字符,这时我们就用到了stringByReplacingOccurrencesOfString方法:

    NSString *str = @"@moxue";
    NSString *first = [str stringByReplacingOccurrencesOfString:@"@" withString:@"h"];//将@替换为h
    NSString *second = [str stringByReplacingOccurrencesOfString:@"@" withString:@""];//去掉字符串@

       另一种方式是:通过自定义一个NSCharacterSet,其中包含要去掉的字符:

NSString *str2 = @"moxue#moxue*moxue    moxue$$$";
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@$# "];//设置需要去掉的字符
    str2 = [str2 stringByTrimmingCharactersInSet:set];//调用方法进行过滤
    NSLog(@"%@",str2);

      另外NSCharacterSet还有一些自己的方法:

 [str2 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去掉两端空格
 [str2 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];//去掉回车  

     字符串切割为数组:

 NSString *name = @"墨雪,望舒,焚天,流星";
 NSArray *nameArr = [name componentsSeparatedByString:@","];

     将上面的数组转化为字符串,以“,”作为分割点:

 NSString *name2 = [nameArr componentsJoinedByString:@","];
原文地址:https://www.cnblogs.com/moxuexiaotong/p/4951101.html