Removing extra "empty" characters from byte array and converting to a string
14,480
I believe this does the same thing:
String emptyRemoved = "he\u0000llo\u0000".replaceAll("\u0000.*", "");
Related videos on Youtube
Author by
user460880
Updated on June 04, 2022Comments
-
user460880 almost 2 years
I was working on this for a while and did not find anything about this on here, so I thought I would post my solution for criticism/usefulness.
import java.lang.*; public class Concat { public static void main(String[] args) { byte[] buf = new byte[256]; int lastGoodChar=0; //fill it up for example only byte[] fillbuf=(new String("hello").getBytes()); for(int i=0;i<fillbuf.length;i++) buf[i]=fillbuf[i]; //Now remove extra bytes from "buf" for(int i=0;i<buf.length;i++) { int bint = new Byte(buf[i]).intValue(); if(bint == 0) { lastGoodChar = i; break; } } String bufString = new String(buf,0,lastGoodChar); //Prove that it has been concatenated, 0 if exact match System.out.println( bufString.compareTo("hello")); } }
-
Mark Peters over 13 yearsI'm calling this not a real question because you posted a solution in the question, basically asking for answers to be questions/criticism. If you want to explore the best way of doing something, properly define the requirements as a question and then post an answer to your own question. That way we can up/down vote it or suggest things in the comments.
-
user460880 over 13 yearsYeah, sorry. This wasn't meant to ask a question as much as it was to share code. Which I find to often lead to much more constructive criticism. And, being a non-CS person, find that it helps when you don't know how to communicate what you want to do.
-
-
user460880 over 13 yearsAwesome, thanks. I figured out how to replace the second "for" loop using your suggestion. But it does require first properly decoding the byte array by specifying a proper charset.
-
cesards over 11 yearsOr adding: new String(content, 0, totalBytesRead, "ISO-8859-1"); I think it does the same!