1

I need to convert String[] to Byte[] in Java. Essentially, I have a space delimited string returned from my database. I have successfully split this String into an array of string elements, and now I need to convert each element into a byte, and produce a byte[] at the end.

So far, the code below is what I have been able to put together but I need some help making this work please, as the getBytes() function returns a byte[] instead of a single byte. I only need a single byte for the string (example string is 0xd1 )

byte[] localbyte = null;
if(nbytes != null)
{
    String[] arr = (nbytes.split(" ")); 
    localbyte = new byte[arr.length];  
    for (int i=0;  i<localbyte.length;  i++) {
        localbyte[i] = arr[i].getBytes();  
    }
}
4

3 回答 3

1

I assume you'd like to split strings like this:

"Hello  world!"

Into "Hello", "world!" instead of "Hello", " ", "world!"

If that's the case, you can simply tweak on the split regex, using this instead:

String[] arr = (nbytes.split(" +"));
于 2012-09-16T02:51:38.563 回答
1

You should be familiar with regular expression. Instead of removing empty string after splitting, you can split the string with one or more white space:

To split a string by space or tab, you can use:

String[] arr = (nbytes.split("\\p{Blank}+"));

E.g.

"Hello \tworld!" 

results in

"Hello","world!"

To split a string by any whitespace, you can use:

String[] arr = (nbytes.split("\\p{Space}+"));

E.g

"Hello \tworld!\nRegular expression" 

results in

"Hello","world!","Regular","expression"
于 2012-09-16T03:24:11.417 回答
0

What about Byte(String string) (Java documentation).
Also you might want to look up Byte.parseByte(string) (doc)

byte[] localbyte = null;
if(nbytes != null)
{
    String[] arr = (nbytes.split(" ")); 
    localbyte = new byte[arr.length];  
    for (int i=0;  i<localbyte.length;  i++) {
        localbyte[i] = new Byte(arr[i]);  
    }
}

Notice:

The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value.

So you might want to catch the NumberFormatException.
If this is not what your looking for maybe you can provide additional information about nbytes ?

Also Michael's answer could turn out helpful: https://stackoverflow.com/a/2758746/1063730

于 2012-09-16T04:03:46.870 回答