对字符串进行的操作

这是在功过工程中用到的一些字符串处理,总结出来方便以后使用,如果大家还有什么特别的需求,请留言,一起研究共同学习

pragma mark --- 汉字转拼音

-(void)chineseWordSwitchIntoPinyin
{
    //汉字转拼音
    NSString *chinese=@"把汉字转换成拼音";
    NSMutableString *pinyin = [chinese mutableCopy];
    //转拼音
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    //去掉音标1234声
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    //转化后的拼音有空格
    //NSString中的stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]方法只是去掉左右两边的空格;
    //去掉字符串中的全部空格
    NSString *strEnd = [pinyin stringByReplacingOccurrencesOfString:@" " withString:@""];//可以去掉空格,注意此时生成的strEnd是autorelease属性的
    NSLog(@"====================%@", strEnd);
}
#pragma mark --- 去掉字符串中间的空格
-(void)removeSpaceInString
{
    NSString *str=@" 把汉字啊水电费 af ksf ajuf 转换成 拼音 ";
    //可以去掉空格,注意此时生成的strEnd是autorelease属性的
    NSString *strEnd = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"====================%@", strEnd);
}

pragma mark --- 字母转大写

-(void)wordSwitchIntoUpper
{
    NSString *student           = @"studentASFAFVWBRVSDFSB";
    NSString *studentUp         = [student uppercaseString];    //大写
    NSString *studentUpFirst    = [student capitalizedString];  //开头大写,其余小写
    NSLog(@"---------%@",student);
    NSLog(@"---------%@",studentUp);
    NSLog(@"---------%@",studentUpFirst);
}

pragma mark --- 字母转小写

-(void)wordSwitchIntoLower
{
    NSString *TEACHER           = @"TEACHERfrfeva";
    NSString *TEACHERLower      = [TEACHER lowercaseString];    //小写
    NSString *TEACHERUpFirst    = [TEACHER capitalizedString];
    NSLog(@"---------%@",TEACHER);
    NSLog(@"---------%@",TEACHERLower);
    NSLog(@"---------%@",TEACHERUpFirst);    
}

pragma mark --- 字符串局部着色

 label.attributedText = [self stringWithColor:[UIColor redColor] range:NSMakeRange(2, 2) string:@"对字符串进行的操作"];

-(NSAttributedString *)stringWithColor:(UIColor *)color range:(NSRange)range string:(NSString *)string
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:string];
    [str addAttribute:NSForegroundColorAttributeName value:color range:range];
    return str;
}

你可能感兴趣的:(对字符串进行的操作)