当前位置: 移动技术网 > IT编程>开发语言>Java > Java 大小写最快转换方式实例代码

Java 大小写最快转换方式实例代码

2019年07月22日  | 移动技术网IT编程  | 我要评论

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 
  } 
} 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!如有疑问请留言,或者到本站社区讨论!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网