美文网首页iOS学习笔记ios开发iOS - 开发技巧
iOS-使用CFStringTransform汉字转拼音

iOS-使用CFStringTransform汉字转拼音

作者: SkyMing一C | 来源:发表于2017-05-04 20:11 被阅读1574次

    Demo_github

    图片源于网络

    在CoreFoundation中提供了CFStringTransform函数。但在 Foundation中却没有相对应的方法。它在CoreFoundation的定义如下:

    /* Perform string transliteration.  The transformation represented by transform is applied to the given range of string, modifying it in place. Only the specified range will be modified, but the transform may look at portions of the string outside that range for context. NULL range pointer causes the whole string to be transformed. On return, range is modified to reflect the new range corresponding to the original range. reverse indicates that the inverse transform should be used instead, if it exists. If the transform is successful, true is returned; if unsuccessful, false. Reasons for the transform being unsuccessful include an invalid transform identifier, or attempting to reverse an irreversible transform.
    
    You can pass one of the predefined transforms below, or any valid ICU transform ID as defined in the ICU User Guide. Note that we do not support arbitrary set of ICU transform rules.
    */
    CF_EXPORT
    Boolean CFStringTransform(CFMutableStringRef string, CFRange *range,  CFStringRef transform, Boolean reverse);
    

    CFStringTransform函数参数解析

    • CFMutableStringRef string

      是要转换的string,比如要转换的中文,同时它是mutable的,因此也可直接作为最终转换后的字符串。

    • CFRange *range

      是要转换的范围,同时输出转换后改变的范围。如果为NULL,视为全部转换。

    • CFStringRef transform

      是指定要进行什么样的转换,可以指定多种语言的拼写转换。在CoreFoundation中CFStringRef 的定义如下:

    /* Transform identifiers for CFStringTransform()
    */
    CF_EXPORT const CFStringRef kCFStringTransformStripCombiningMarks;//去掉重音和变音符号
    CF_EXPORT const CFStringRef kCFStringTransformToLatin;//非英文文本转换为拉丁字母
    CF_EXPORT const CFStringRef kCFStringTransformFullwidthHalfwidth;
    CF_EXPORT const CFStringRef kCFStringTransformLatinKatakana;
    CF_EXPORT const CFStringRef kCFStringTransformLatinHiragana;
    CF_EXPORT const CFStringRef kCFStringTransformHiraganaKatakana;
    CF_EXPORT const CFStringRef kCFStringTransformMandarinLatin;
    CF_EXPORT const CFStringRef kCFStringTransformLatinHangul;
    CF_EXPORT const CFStringRef kCFStringTransformLatinArabic;
    CF_EXPORT const CFStringRef kCFStringTransformLatinHebrew;
    CF_EXPORT const CFStringRef kCFStringTransformLatinThai;
    CF_EXPORT const CFStringRef kCFStringTransformLatinCyrillic;
    CF_EXPORT const CFStringRef kCFStringTransformLatinGreek;
    CF_EXPORT const CFStringRef kCFStringTransformToXMLHex;
    CF_EXPORT const CFStringRef kCFStringTransformToUnicodeName;
    CF_EXPORT const CFStringRef kCFStringTransformStripDiacritics CF_AVAILABLE(10_5, 2_0);
    
    • Boolean reverse

      该转换是否必须是可逆向转换的。如果转换成功就返回true,否则返回false。

    CFStringTransform函数使用

    • 如果要进行汉字到拼音的转换,我们只需要将transform设定为kCFStringTransformMandarinLatin或者kCFStringTransformToLatin(kCFStringTransformToLatin也可适用于非汉字字符串):
            //1.先转换为带声调的拼音
            if(CFStringTransform((__bridge CFMutableStringRef)pinYin, NULL, kCFStringTransformMandarinLatin, NO)) {
                NSLog(@"带声调的pinyin: %@", pinYin);
            }
      

      其输出结果如下:

      带声调的pinyin: hàn zì zhuǎn pīn yīn
      
    • 如果要去掉音标,我们只需要将transform设定为kCFStringTransformStripDiacritics :
       //2.再转换为不带声调的拼音
      if (CFStringTransform((__bridge CFMutableStringRef)pinYin, NULL, kCFStringTransformStripDiacritics, NO)) {
           NSLog(@"不带声调的pinyin: %@", pinYin);
       }      
      

      其输出结果如下:

      不带声调的pinyin: han zi zhuan pin yin
      
    • 以上转成的拼音字符串,系统会将每个汉字的拼音用空格分隔开,如果要去掉空白字符和换行字符,我们要对转换的拼音字符串进行额外的操作:
            //3.去除掉首尾的空白字符和换行字符
            pinYinStr = [pinYin stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            //4.去除掉其它位置的空白字符和换行字符
            pinYinStr = [pinYinStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
            pinYinStr = [pinYinStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            pinYinStr = [pinYinStr stringByReplacingOccurrencesOfString:@" " withString:@""];
      

      其输出结果如下:

      去掉空白字符和换行字符的pinyin:   hanzizhuanpinyin
    
    • 字符串大小写转换,首字母大写(NSString.h)
      @property (readonly, copy) NSString *uppercaseString;//大写
      @property (readonly, copy) NSString *lowercaseString;//小写
      @property (readonly, copy) NSString *capitalizedString;//首字母大写
      
      如果是要自己实现的话,需要考虑一下ASCII码,大小写之间的差值是32,A是65,a是97,代码如下:
      -(NSString *)toLower:(NSString *)str{
       for (NSInteger i=0; i<str.length; i++) {
           if ([str characterAtIndex:i]>='A'&[str characterAtIndex:i]<='Z') {
               //A  65  a  97
               char  temp=[str characterAtIndex:i]+32;
               NSRange range=NSMakeRange(i, 1);
               str=[str stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"%c",temp]];
           }
       }
       return str;
      }
      -(NSString *)toUpper:(NSString *)str{
       for (NSInteger i=0; i<str.length; i++) {
           if ([str characterAtIndex:i]>='a'&[str characterAtIndex:i]<='z') {
               //A  65  a  97
               char  temp=[str characterAtIndex:i]-32;
               NSRange range=NSMakeRange(i, 1);
               str=[str stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"%c",temp]];
           }
       }
       return str;
      }
      
    • 字符串与数组相互转换
      NSArray *arrays = @[@"1,2,3,4,5,6"];
      NSString *string = [arrays componentsJoinedByString:@","];//数组转换成字符串,根据@","
      NSArray *array = [string componentsSeparatedByString:@","];//字符串转换成数组,根据@","
      NSLog(@"转换成的string:--- %@",string);
      NSLog(@"转换成的array:--- %@",array);
    

    示范代码:

    + (NSString *)transformPinYinWithString:(NSString *)chinese
    {
         NSString  * pinYinStr = [NSString string];
        if (chinese.length){
            NSMutableString * pinYin = [[NSMutableString alloc]initWithString:chinese];
            //1.先转换为带声调的拼音
            if(CFStringTransform((__bridge CFMutableStringRef)pinYin, NULL, kCFStringTransformMandarinLatin, NO)) {
                NSLog(@"带声调的pinyin: %@", pinYin);
            }
            //2.再转换为不带声调的拼音
            if (CFStringTransform((__bridge CFMutableStringRef)pinYin, NULL, kCFStringTransformStripDiacritics, NO)) {
                NSLog(@"不带声调的pinyin: %@", pinYin);
            }
            //3.去除掉首尾的空白字符和换行字符
            pinYinStr = [pinYin stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            //4.去除掉其它位置的空白字符和换行字符
            pinYinStr = [pinYinStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
            pinYinStr = [pinYinStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            pinYinStr = [pinYinStr stringByReplacingOccurrencesOfString:@" " withString:@""];
            NSLog(@"去掉空白字符和换行字符的pinyin: %@", pinYinStr);
            [pinYinStr capitalizedString];
    
        }
        return pinYinStr;
    }
    
    

    Demo_github

    参考文章

    相关文章

      网友评论

      • iCoder_木子弋:这个有问题,对于多音字处理有问题,比如我录入“中国银行”,转换出来是“zhongguoyinxing”,最后一个多音字不对。我感觉这个方法处理非多音字还是没问题的
        SkyMing一C:@iCoder_木子弋 没 CFStringTransform是不支持多音字的
        iCoder_木子弋:@半雨残烟墨冷倾城 你没有试这个三方吧?这个三方也是存在相同的问题的!Thanks all the same!
        SkyMing一C:多音字可以用这个第三方 https://github.com/kimziv/PinYin4Objc

      本文标题:iOS-使用CFStringTransform汉字转拼音

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