Java 汉字转拼音首字母缩写

以下代码不支持多音字,请慎重使用。

package com.tc.sjcj.TC_Provider;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;

public class SingleConvertPinyinClass {

    /**
     * 汉字转成拼音缩写
     * 
     * @param activity
     *            活动界面
     * @param chinese
     *            要转的中文汉字
     * @return
     */
    public String chineseParseToPinYin(Context context, String chinese) {
        ContentValues values = new ContentValues();
        Uri rawContactUri = context.getContentResolver().insert(RawContacts.CONTENT_URI, values);
        long rawContactId = ContentUris.parseId(rawContactUri);
        String name = chinese;
        if (name.length() != 0) {
            values.clear();
            values.put(Data.RAW_CONTACT_ID, rawContactId);
            values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
            values.put(StructuredName.GIVEN_NAME, name);
            context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
            String result = hanziToPinyin(context, rawContactId);
            delete(context, rawContactId);
            return result;
        } else {
            return null;
        }
    }

    private String hanziToPinyin(Context context, long rawContactId) {
        String result = "";
        String Where = ContactsContract.RawContacts.CONTACT_ID + " =" + rawContactId;
        String[] projection = { "sort_key" };
        Cursor cur = context.getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, Where, null, null);
        int pinyin1 = cur.getColumnIndex("sort_key");
        cur.moveToFirst();
        String pinyin = cur.getString(pinyin1);
        boolean tried = true;
        for (int i = 0; i < pinyin.length(); i++) {
            String temp = pinyin.substring(i, i + 1);
            if (temp.matches("[a-zA-Z]") && tried == true) {
                result = result + temp;
                tried = false;
            } else if (temp.matches("[a-zA-Z]") == false) {
                tried = true;
            }
        }
        String message = result.toUpperCase();
        return message;
    }

    private void delete(Context context, long rawContactId) {
        context.getContentResolver().delete(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), null, null);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值