PinyinUtil

Introduction

The Pinyin utility class was previously located in the core package of Hutool, but it was found that implementing related functionalities required a large dictionary, which made it cumbersome to include in the core package.

To facilitate ease of use, Hutool encapsulates a Pinyin facade to compatible with the following Pinyin libraries:

  1. TinyPinyin
  2. JPinyin
  3. Pinyin4j

Similar to other facade modules, Hutool uses the SPI mechanism to identify the library being used. For example, if you want to use Pinyin4j, simply include the jar file, and Hutool will automatically identify it.

Usage

Including the library

Below are the pom coordinates for the Pinyin libraries supported by Hutool. You can choose to include any one of them in your project. If multiple libraries are included, Hutool will select the first one in the above order for use.

<dependency>
 <groupId>io.github.biezhi</groupId>
 <artifactId>TinyPinyin</artifactId>
 <version>2.0.3.RELEASE</version>
</dependency>
<dependency>
 <groupId>com.belerweb</groupId>
 <artifactId>pinyin4j</artifactId>
 <version>2.5.1</version>
</dependency>
<dependency>
 <groupId>com.github.stuxuhai</groupId>
 <artifactId>jpinyin</artifactId>
 <version>1.1.8</version>
</dependency>

Usage

  1. Getting Pinyin
// "ni hao"
String pinyin = PinyinUtil.getPinyin("你好", " ");

Here, the defined separator is a space. You can also customize the separator according to your needs or use "" for no separator.

  1. Getting the first letter of Pinyin
// "h, s, d, y, g"
String result = PinyinUtil.getFirstLetter("H是第一个", ", ");
  1. Customizing the Pinyin library (Pinyin engine)
Pinyin4jEngine engine = new Pinyin4jEngine(); 
// "ni hao h" 
String pinyin = engine.getPinyin("你好h", " ");