[英]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.给定一个 char[],需要用空 String 替换 char[] 中的一个字符序列。 I am doing it by converting char[] to string and using replace method to achieve it.
我通过将 char[] 转换为字符串并使用替换方法来实现它。 But I need to avoid converting char[] to String as this has sensitive data.
但我需要避免将 char[] 转换为 String,因为它包含敏感数据。 How to replace it in the char[] without converting to String?
如何在不转换为字符串的情况下在 char[] 中替换它?
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)
. Matcher
接受一个CharBuffer
,您可以使用CharBuffer.wrap(chars)
轻松获得它。 For the output, you can use a StringBuilder
which internally does not use strings.对于输出,您可以使用内部不使用字符串的
StringBuilder
。 When you are done processing, you can get the characters out with the getChars(...)
method.完成处理后,您可以使用
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.