How does swift use the system library to translate Chinese characters into pinyin

  • 2020-05-30 21:10:48
  • OfStack

preface

It is believed that when you search iOS 1, you will encounter the situation of searching for keywords through pinyin. At this time, our judgment needs to convert Chinese characters into pinyin. Sometimes, we also need to obtain the capital abbreviation of pinyin.

Some of the third party library can complete the conversion of Chinese characters to pinyin, but the system library can also support pinyin conversion, so here is a simple introduction to the use of system library conversion method 1.

The method is as follows:

The best way to add the judging function is to add one extension to the String class. The code is as follows:


extension String {}

Then step 1 is to determine if there are any Chinese characters in the string:


extension String {
 func isIncludeChinese() -> Bool {
  for ch in self.unicodeScalars {
   //  Chinese character range: 0x4e00 ~ 0x9fff
   if (0x4e00 < ch.value && ch.value < 0x9fff) {
    return true
   }
  }
  return false
 }
}

Step 2 is to convert to pinyin:


func transformToPinyin() -> String {
 let stringRef = NSMutableString(string: self) as CFMutableString
 //  Convert to pinyin with phonetic symbols 
 CFStringTransform(stringRef,nil, kCFStringTransformToLatin, false);
 //  Remove the phonetic symbol 
 CFStringTransform(stringRef, nil, kCFStringTransformStripCombiningMarks, false);
 let pinyin = stringRef as String;

 return pinyin
}

In this way, the pinyin string will be separated by a space between the pinyin of each Chinese character, and the function to remove the space will be added:


func transformToPinyinWithoutBlank() -> String {
 var pinyin = self.transformToPinyin()
 //  Remove the blank space 
 pinyin = pinyin.stringByReplacingOccurrencesOfString(" ", withString: "")
 return pinyin
}

The last method is to get the uppercase initial:


func getPinyinHead() -> String {
 //  String conversion capitalizes the first letter 
 let pinyin = self.transformToPinyin().capitalizedString
 var headPinyinStr = ""

 //  Gets all uppercase letters 
 for ch in pinyin.characters {
  if ch <= "Z" && ch >= "A" {
   headPinyinStr.append(ch)
  }
 }
 return headPinyinStr
}

I hope you found that useful.

conclusion


Related articles: