Reputation: 5600
I've searched around the Java sections but haven't found an adequate answer. I'm testing out some basic (extremely basic) object obscuring for serialization just to get the feel of it.
To de-obscure my object I need to remove the added character that I've put on my object.
E.g
Profile name is original "John"
I then turn it into, "#J/oH@n"
I would then need to reverse the latter into the original by removing the symbols. However I couldn't find a suitable/efficient way of doing so.
Please do keep in mind that my list of symbols could be saved in char[] or just one String like so:
char[] obcChars = {'#', ';', '"', '¬', '¦', '+', ';'
, '/', '.', '^', '&', '$', '*'
, '[', '@', '-', '~', ':'};
String s = new String(obcChars);
Whichever method you need to use to facilitate your answer is fine by me! I'd also like to thank you in advance.
Upvotes: 0
Views: 90
Reputation: 10945
You can create a regular expression which contains the characters you want to remove:
char[] obcChars = {'#', ';', '"', '¬', '¦', '+', ';'
, '/', '.', '^', '&', '$', '*'
, '[', '@', '-', '~', ':'};
StringBuilder sb = new StringBuilder();
sb.append(obcChars[0]);
for (int i=1; i<obcChars.length; i++) {
sb.append("|\\");
sb.append(obcChars[i]);
}
// sb now contains the regex #|\;|\"|\¬|\¦|\+|\;|\/|\.|\^|\&|\$|\*|\[|\@|\-|\~|\:
Then just use the String#replaceAll()
method to take them out of your input string:
String oName = "#J/oH@n";
System.out.println(oName.replaceAll(sb.toString(), "")); // prints JoHn
This will be useful if you know which characters you want to remove, and they are a limited subset of non-alpha. If you just want to trim out all non-letters, see @alfasin's answer for a much simpler solution to that problem.
Upvotes: 1
Reputation: 53525
You can use regex:
String obcChars = "[^a-zA-Z]";
String word = "#J/oH@n";
word = word.replaceAll(obcChars, "");
System.out.println("word = " + word);
OUTPUT
word = JoHn
Upvotes: 2
Reputation: 4792
To remove characters at an index from a String you have to use a StringBuilder which is a mutable version of a String (you can change StringBuilders)
String s = "Hello World";
StringBuilder sb = new StringBuilder(s);
sb.removeCharAt(sb.indexOf('e'));
s = sb.toString();
System.out.println(s); // Prints Hllo World
Upvotes: 2