Java 大小寫最快轉換方式實例代碼
這里直接給出實現代碼,在代碼中注釋都很清楚,不多做介紹。
Java代碼
package io.mycat;
import java.util.stream.IntStream;
/**
* 小寫字母的 'a'=97 大寫字母 A=65 更好相差32利用這個差進行大小寫轉換
* @author : Hpgary
* @date : 2017年5月3日 10:26:26
* @mail: hpgary@qq.com
* */
public class StringUtils {
protected final static byte[] CHAR_TYPE = new byte[512];
protected final static byte CHARACTER_DIFFER = 32;
static {
/**
* 先將大寫字母放入 CHAR_TYPE 中,將大寫轉換成為小寫字母
* */
IntStream.rangeClosed('A', 'Z').forEach(c -> CHAR_TYPE[c] = (byte) (c + CHARACTER_DIFFER));
/**
* 將小寫字母放入 CHAR_TYPE,存值為小寫字母
* */
IntStream.rangeClosed('a', 'z').forEach(c -> CHAR_TYPE[c] = (byte) (c));
}
public static byte[] toUpperCase(String src) {
byte[] bytes = src.getBytes();
for (int x = 0; x < bytes.length; x++) {
int tmpLen = bytes[x] << 1;
if (tmpLen < CHAR_TYPE.length && tmpLen >= 0) {
byte b = CHAR_TYPE[bytes[x]];
if (b != 0) {
bytes[x] = (byte) (b - CHARACTER_DIFFER);
}
}
}
return bytes;
}
public static byte[] toLowerCase(String src) {
byte[] bytes = src.getBytes();
for (int x = 0; x < bytes.length; x++) {
int tmpLen = bytes[x] << 1;
if (tmpLen < CHAR_TYPE.length && tmpLen >= 0) {
byte b = CHAR_TYPE[bytes[x]];
if (b != 0) {
bytes[x] = b;
}
}
}
return bytes;
}
public static void main(String[] args) {
int count = 100000 ;
String str = "fdajfadSKfj1221SDKfdasfdsafjdsafjlsadjfkl;sdajflksadjlfkjasdlk;fjasdklfasdA" ;
long time2 = System.currentTimeMillis();
for (int x = 0; x < count; x++) {
str.toUpperCase();
}
System.out.println(System.currentTimeMillis() - time2); //51 - 53
long time1 = System.currentTimeMillis();
for (int x = 0; x < count; x++) {
toUpperCase(str) ;
}
System.out.println(System.currentTimeMillis() - time1); // 35-37
}
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!如有疑問請留言,或者到本站社區討論!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。