问题
Is there any string type/class in Java (standard or otherwise) that is based on an array of the 8-bit byte type, and not the 16-bit char type?
I really like the std::string type in C++, as it works very well with parsing base256 (binary) data...
I went ahead and wrote a little class that provides most of the features I need (below), but a better one would be appreciated!
public class stdstring extends Object {
private byte [] bytedata;
public stdstring() {
bytedata = new byte[0];
}
public stdstring(byte[] bytes) {
bytedata = bytes;
}
public stdstring(byte[] bytes, int offset, int length) {
bytedata = new byte[length];
System.arraycopy(bytes,offset,bytedata,0,length);
}
public stdstring(String string) throws UnsupportedEncodingException {
bytedata = new byte[string.length()];
bytedata = string.getBytes("ISO-8859-1");
}
public void assign(byte[] bytes) {
bytedata = new byte[bytes.length];
bytedata = bytes;
}
public void assign(byte[] bytes, int offset, int length) {
bytedata = new byte[length];
System.arraycopy(bytes,offset,bytedata,0,length);
}
public void assign(String string) throws UnsupportedEncodingException {
bytedata = string.getBytes("ISO-8859-1");
}
public int length() {
return bytedata.length;
}
public byte[] getBytes() {
byte [] copy = new byte[bytedata.length];
System.arraycopy(bytedata,0,copy,0,bytedata.length);
return copy;
}
public byte[] getBytes(int offset, int length) {
byte [] piece = new byte[length];
System.arraycopy(bytedata,offset,piece,0,length);
return piece;
}
public byte getByte(int offset) {
byte b = bytedata[offset];
return b;
}
public stdstring substring(int offset, int length) {
stdstring sub = new stdstring(bytedata, offset, length);
return sub;
}
public boolean equals(stdstring string) {
if (bytedata.length != string.length()) { return false; }
for (int i = 0; i < bytedata.length; ++i) {
if (bytedata[i] != string.getByte(i)) { return false; }
}
return true;
}
}
来源:https://stackoverflow.com/questions/33617245/is-there-a-string-type-in-java-based-on-on-an-8-bit-byte-array