KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
What is the fastest way to strip all non-printable characters from a String in Java? So far I've tried and measured on 138-byte, 131-character String: String's replaceAll() - slowest method 517009 results / sec Precompile a Pattern, then use Matcher's replaceAll() 637836 results / sec Use StringBuffer, get codepoints using codepointAt() one-by-one and append to StringBuffer 711946 results / sec Use StringBuffer, get chars using charAt() one-by-one and append to StringBuffer 1052964 results / sec Preallocate a char[] buffer, get chars using charAt() one-by-one and fill this buffer, then convert back to String 2022653 results / sec Preallocate 2 char[] buffers - old and new, get all chars for existing String at once using getChars() , iterate over old buffer one-by-one and fill new buffer, then convert new buffer to String - my own fastest version 2502502 results / sec Same stuff with 2 buffers - only using byte[] , getBytes() and specifying encoding as "utf-8" 857485 results / sec Same stuff with 2 byte[] buffers, but specifying encoding as a constant Charset.forName("utf-8") 791076 results / sec Same stuff with 2 byte[] buffers, but specifying encoding as 1-byte local encoding (barely a sane thing to do) 370164 results / sec My best try was the following: char[] oldChars = new char[s.length()]; s.getChars(0, s.length(), oldChars, 0); char[] newChars = new char[s.length()]; int newLen = 0; for (int j = 0; j < s.length(); j+
Tags (comma-separated)
Save Edits
Cancel