簡體   English   中英

java - 如何在字符數組中替換字符序列而不將其轉換為字符串

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

給定一個 char[],需要用空 String 替換 char[] 中的一個字符序列。 我通過將 char[] 轉換為字符串並使用替換方法來實現它。 但我需要避免將 char[] 轉換為 String,因為它包含敏感數據。 如何在不轉換為字符串的情況下在 char[] 中替換它?

當前代碼,

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

Matcher接受一個CharBuffer ,您可以使用CharBuffer.wrap(chars)輕松獲得它。 對於輸出,您可以使用內部不使用字符串的StringBuilder 完成處理后,您可以使用getChars(...)方法獲取字符。

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM