自己写个native2的字码转化

星期日, 2008-12-28 | Author: liyz | JAVA-and-J2EE | 3,476 views

jdk里面提供了个国际码的转化命令native2,但是自己在程序中使用就不能老是调用命令行

自己动手实现个,首先想到的是移位操作,朋友看了我的代码说,不用移位也可以,就直接装换int就好了

呵呵,反正看着>>>移位和&的操作符有点怵,就两种都写了下,效果一样的,抓换里面对通用的没有转

比如A-Z等,主要也是为了转中文的嘛

贴出code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.liyz.native2;
 
public class Native2 {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String sea = "AAAAPomelo Lee";
		String newStr = convert(sea);
		System.out.println(newStr);
 
		String newStrMove = convertMove(sea);
		System.out.println(newStrMove);
	}
 
	/*
	 * ---I like use this method,but have other --- if you want covert
	 * a-z,please remove if(c>255)
	 */
	private static String convertMove(String str) {
		String tmp;
		StringBuffer sb = new StringBuffer(1000);
		char c = 0;
		int i, j;
		sb.setLength(0);
		for (i = 0; i < str.length(); i++) {
			c = str.charAt(i);
 
			if (c > 255) {
				sb.append("\\u");
				j = (c >>> 8);
				tmp = Integer.toHexString(j);
				if (tmp.length() == 1)
					sb.append("0");
				sb.append(tmp);
 
				j = (c &#038; 0xFF);
				tmp = Integer.toHexString(j);
				if (tmp.length() == 1)
					sb.append("0");
				sb.append(tmp);
			} else {
				sb.append(c);
			}
		}
		return (new String(sb));
	}
 
	/*
	 * method second,use int convert
	 */
	private static String convert(String str) {
		String tmp;
		StringBuffer sb = new StringBuffer(1000);
		sb.setLength(0);
		char c = 0;
		for (int i = 0; i < str.length(); i++) {
			c = str.charAt(i);
			if (c > 255) {
				sb.append("\\u");
				tmp = Integer.toHexString((int) c);
				if (tmp.length() < 4) {
					for (int k = 0; k < 4 - tmp.length(); k++) {
						sb.append("0");
					}
				}
				sb.append(tmp);
			} else {
				sb.append(c);
			}
		}
		return (new String(sb));
	}
}

Tags: ,

文章作者: liyz

本文地址: https://www.pomelolee.com/196.html

除非注明,Pomelo Lee文章均为原创,转载请以链接形式标明本文地址

No comments yet.

Leave a comment

Search

文章分类

Meta