Pages

Friday, March 8, 2013

Simple Encoding and Decoding for Alpha Numeric String

Below is the code in java for alpha numeric string encoding and  decoding.


public class EncodeDecode {

private String getString() {
StringBuffer chrStr = new StringBuffer();

for (int x = 0; x <= 25; x++) {
int ch = 65 + x;
chrStr.append((char) ch);
}
for (int x = 0; x <= 9; x++) {
int ch = x;
chrStr.append(ch);
}
for (int x = 0; x <= 25; x++) {
int ch = 97 + x;
chrStr.append((char) ch);
}
return chrStr.toString();
}

private String encodedString(){
String chrStr = getString();
int from = 13;
int to = (chrStr.toString().length());
return chrStr.substring(from, to) + chrStr.substring(0, from);
}

public String decode(String input) {
String strDecode = "";

String chrStr = getString();

String abTo = encodedString();

for (int i = 0; i < input.length(); i++) {
int y = abTo.indexOf(input.charAt(i));

if (y == 0) {
strDecode = strDecode + input.charAt(i);
} else {
strDecode = strDecode + chrStr.charAt(y);
}
}
return strDecode;
}

public String encode(String input) {
String strEncode = "";
String chrStr = getString();

String abTo = encodedString();

for (int i = 0; i < input.length(); i++) {
int y = chrStr.indexOf(input.charAt(i));

if (y == 0) {
strEncode = strEncode + input.charAt(i);
} else {
strEncode = strEncode + abTo.charAt(y);
}
}

return strEncode;
}

No comments:

Post a Comment