iOS-使用CFStringTransform汉字转拼音

Demo_github

iOS-使用CFStringTransform汉字转拼音_第1张图片
图片源于网络

在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='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='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

参考文章

  • 使用CFStringTransform将汉字转换为拼音

  • iOS-使用CFStringTransform将汉字转换为拼音

你可能感兴趣的:(iOS-使用CFStringTransform汉字转拼音)