简体   繁体   中英

How to replace Char Sequence in a char array without converting it to String in java

Given a char[], need to replace a char sequence in the char[] with empty String. I am doing it by converting char[] to string and using replace method to achieve it. But I need to avoid converting char[] to String as this has sensitive data. How to replace it in the char[] without converting to String?

Current code,

char[] chars = charArray;
String str = String.valueOf(chars)
                        .replaceAll("(.*?)-----", "")
                        .replaceAll("\\s", "");

A Matcher accepts a CharBuffer which you can easily get with CharBuffer.wrap(chars) . For the output, you can use a StringBuilder which internally does not use strings. When you are done processing, you can get the characters out with the getChars(...) method.

char[] chars = {'a','b','c','d','-','-','-','-','-','e','f','g','h'};

Pattern p = Pattern.compile("(.*?)-----");
Matcher m = p.matcher(CharBuffer.wrap(chars));

StringBuilder sb = new StringBuilder();
while (m.find()) {
    m.appendReplacement(sb, "");
}
m.appendTail(sb);

chars = new char[sb.length()];
sb.getChars(0, sb.length(), chars, 0);

System.out.println(Arrays.toString(chars)); // output: [e, f, g, h]

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