We’ve previously shown how to create an MD5 sum for a file. If you don’t have a file and instead just need an MD5 sum for a byte array then you can achieve it using the following code.
// Data is the byte array we need an MD5 sum for
byte data = getDataFromWhereever();
// Get an MD5 implementation of MessageDigest
MessageDigest md = MessageDigest.getInstance("MD5");
// Convert the MD5 byte array to a hex string
String md5 = new BigInteger(1, md.digest(data)).toString(16);
The following code will split the string into chunks, each of length ‘nchars’ (except potentially the last chunk)
int len = string.length();
for (int i=0; i<len; i+=nchars)
String part = string.substring(i, Math.min(len, i + nchars)));
Another more exotic option uses regular expression and the spit() method. The number of dots in the regexp controls the length of each part.
// Splits string into 3 character long pieces.
String parts = string.split("(?<=\\G...)");
See how to fill a string with a character for how to dynamically generate a regexp for any number of characters. Though I’d probably go with the first method.
Java 1.5 added a replace() method that could be used to replace all occurrences of a string wiuth another string
s = s.replace(" ", "");
Prior to 1.5 you can use a regular expression with the replaceAll() method to achieve that.
s = s.replaceAll(" ", "");
// Or to replace all whitespace
s = s.replaceAll("\\s", "");
Let us know if you need a different solution.