简体   繁体   中英

Removing desired character from a String (From a String or char[])

Removing desired character from a String (From a String or char[])

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.

Eg

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.

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

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

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

Note

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM