Java中参数字符串的压缩和解压缩

时间:2014-02-20 05:56:57

标签: java string arguments compression

我无法想出一种在Java中解压缩String的方法。这是我正在使用的基本Java类,所以它只需要基本的命令,没有什么太花哨的。它能够输入的目标

C:\>java Compress -c aaaabbbbbcc

在命令提示符下,它将打印a4b5c2(就像压缩参数字符串一样)。

另一个目标是输入

C:\>java Compress -d a5b7c4

它将打印aaaaabbbbbbbcccc(就像它会解压缩参数String)。减压是我遇到的问题。这是我的代码,我得到的任何帮助都非常感谢。

import java.util.*;

public class Compress {
    public static void main(String args[]) {

        Scanner scan = new Scanner(System.in);
        String originalString = scan.nextLine();
        int number = scan.nextInt();

        if (args[0].equals("-c")) {
            System.out.println("compress");
            compress(originalString);
        }

        else if (args[0].equals("-d")) {
            System.out.println("decompress");
            decompress(originalString);
        } else {
            System.out.println("Compress program by Kelsey Faram");
            System.out.println("usage: java Compress [-c,-d] < inputFile > outputFile");
        }
    }

    public static void compress(String originalString) {
        int count = 0;
        char comp = originalString.charAt(0);
        for (int i = 0; i < originalString.length(); i++) {
            originalString.charAt(i);

            if (comp == originalString.charAt(i))
                count++;
            else {
                System.out.print(comp + "" + count);
                comp = originalString.charAt(i);
                count = 1;
            }
        }
        System.out.println(comp + "" + count);
    }

    public static void decompress(String originalString) {

    }
}

1 个答案:

答案 0 :(得分:0)

Quick Code for you..


public static void decompress(String originalString)
{
        StringBuffer finalString = new StringBuffer();;
        char previouschar = originalString.charAt(0);
        for(int i=1; i < originalString.length(); i+=2){
                for(int j = 0 ; j< Integer.parseInt(""+originalString.charAt(i));j++) {
                    finalString.append(previouschar);
                }               
                if(i+1 < originalString.length())
                {
                    previouschar=originalString.charAt(i+1);
                }
        }
        System.out.println(finalString.toString());
}