欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java实现的一个简单的字符串压缩算法源码

程序员文章站 2024-03-14 14:03:46
...

将做工程过程经常用到的一些代码珍藏起来,如下的代码是关于Java实现的一个简单的字符串压缩算法的代码,希望能对各朋友也有用。

public class Contraction {

public static String tempString = "acdesfghsadajfkqsfab";


public static void main(String[] args) {
  System.out.println("压缩前字符串内容:"+tempString);
  System.out.println("压缩前字符串大小:"+tempString.length());
  
  String resultString = compactString(tempString);
  System.out.println("压缩后字符串内容:"+resultString);
  System.out.println("压缩后字符串大小:"+resultString.length());
  
  String convertString = decompressionString(resultString);
  System.out.println("解压后字符串内容:"+convertString);
  System.out.println("解压后字符串大小:"+convertString.length());
}

public static String decompressionString(String tempString){
  char[] tempBytes = tempString.toCharArray();
  StringBuffer sb = new StringBuffer();
  for (int i = 0; i < tempBytes.length; i++) {
   char c = tempBytes;
   char firstCharacter = (char) (c >>> 8);
   char secondCharacter = (char) ((byte)c);
   sb.append(firstCharacter);
   if(secondCharacter != 0)
    sb.append(secondCharacter);
  }
  return sb.toString();
}


public static String compactString(String tempString) {
  StringBuffer sb = new StringBuffer();
  byte[] tempBytes = tempString.getBytes();
  for (int i = 0; i < tempBytes.length; i+=2) {
   char firstCharacter = (char)tempBytes;
   char secondCharacter = 0;
   if(i+1<tempBytes.length)
    secondCharacter = (char)tempBytes[i+1];
   firstCharacter <<= 8;
   sb.append((char)(firstCharacter+secondCharacter));
  }
  return sb.toString();
}
}