字符大小写转换,汉字转拼音
汉字转拼音使用到了 pinyin4j
maven依赖:
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
或者:
<dependency>
<groupId>net.sourceforge.pinyin4j</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
/**
* 中文转汉语拼音
* @param chinese
* @param isPure true:只保留中文和英文 false:保留中英文和其他字符
* @return 拼音全部小写,拼音之间以空格分隔
*/
public static String chinesePaseSpell(String chinese,boolean isPure) {
StringBuilder result = new StringBuilder();
if(StringUtils.isNotBlank(chinese)) {
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
for (int i = 0; i < chinese.length(); i++) {
char c = chinese.charAt(i);
try {
if (String.valueOf(c).matches("[\u4e00-\u9fa5]+")){// 如果字符是中文,则将中文转为汉语拼音
result.append(PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat)[0]).append(HELPERSPACE);
} else if(String.valueOf(c).matches("[a-zA-Z]")) {//如果字符是英文,则直接追加
result.append(String.valueOf(c));
} else {// 如果字符不是中英文,则进行判断
result.append(isPure ? "" : String.valueOf(c));
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
}
}
return result.toString().trim();
}
/**
* 根据空格分割字符串,返回每个单词首字母拼接的字符串
*/
public static String getFirstCharBySpace(String str) {
if(StringUtils.isBlank(str)) return str;
StringBuilder result = new StringBuilder();
String[] words = str.split(HELPERSPACE);
for(String word : words) {
if(StringUtils.isBlank(word)) continue;
result.append(word.charAt(0));
}
return result.toString();
}
/**转大写**/
private static char charToUpperCase(char ch){
if(ch <= 122 && ch >= 97){
ch -= 32;
}
return ch;
}
/***转小写**/
private char charToLowerCase(char ch){
if(ch <= 90 && ch >= 65){
ch += 32;
}
return ch;
}
/**设置xml文件属性的值 (xml文件是一个字符串的形式)*/
public static String resetXmlProperty(String xmlStr,String companySpell,String projectName){
//需要加入相应的try catch
StringReader sr = new StringReader(xmlStr);
InputSource is = new InputSource(sr);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc = builder.parse(is);
NodeList nodes = doc.getElementsByTagName("category");
for(int i=0;i<nodes.getLength();i++){
Element category=(Element) nodes.item(i);
String oldValue = category.getAttribute("clazz");
//修改属性
category.setAttribute("clazz", "目标值");
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
t.transform(new DOMSource(doc), new StreamResult(bos));
xmlStr = bos.toString();
return xmlStr;
}