4

I am using a JNI API (that i can't change) that return a fixed size char array that represent a string.

I am converting it to String with String.valueOf(char [])

The problem is that i can receive an array like this {'a','b','c','\0','\0','\0'}

Using valueOf() keeps the trailing NULLs and a I get a wrong string.

Is there a simple way to convert such and array to string and removing NULLs?

1
  • 1
    Those are not trailing zeros. Those are NULL characters. I corrected the title and body of your Question. Commented May 20, 2019 at 21:46

3 Answers 3

6
String s = String.valueOf(bits).trim();

just trim the string it'll get rid of all *leading & *trailing white space.

Sign up to request clarification or add additional context in comments.

4 Comments

Assuming you're ok with trimming leading whitespace too.
This is for this kind of trick that I was asking. @shmosel the reviewer ;) that's ok is my case
For future readers: String.trim() removes all leading and trailing characters that are equal to or below the space (<= 0x20); that includes control characters.
Trim is quite dangerous if you're chunking arrays (which was my case) - it can trim whitespaces like \n or space - which normally you want to preserve this. I voted for Karol's Dowbecki answer.
3

Normally you would get both an array and a length variable that tells how many characters are to be read from the array. If you don't have length variable you can find it with a loop and use new String(char[], int, int) constructor:

char[] arr = {'a','b','c','\0','\0','\0'};
int len = 0;
do {
  len++;
} while (arr.length > len && arr[len] != '\0');
String s = new String(arr, 0 ,len);
System.out.println(s); // abc

3 Comments

You're assuming it can't start with a \0. And that there won't be any in middle.
You're also assuming there's at least one trailing \0.
thx but I was asking for a trick that i wasn't aware like @mavriksc. You answer stay nice for leading space
-1

I did it like this: Since the nulls are only at the end of the charArray, I went through the array backward and counted how many nulls it had. Then I iterated through the array using its length minus the number of nulls as the upper limit in the for next loop and built the final string without the trailing nulls.

Like this:

public String getStringFromBufferedCharArray(char[] cArray) {
    StringBuilder finalString = new StringBuilder();
    int count = 0;
    for (int x = cArray.length - 1; x >= 0; x--) {
        if ((int) cArray[x] == 0) count++;
        else break;
    }

    int end = cArray.length - count;

    for (int x = 0; x < end; x++) {
        finalString.append(cArray[x]);
    }
    return finalString.toString();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.