Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java null char in string

I'm trying to build a string in Java which will be at maximum 3 long and at minimum 1 long.

I'm building the string depending on the contents of a integer array and want to output a null character in the string if the contents of the array is -1. Otherwise the string will contain a character version of the integer.

    for (int i=0; i < mTypeSelection.length; i++){
        mMenuName[i] = (mTypeSelection[i] > -1 ? Character.forDigit(mTypeSelection[i], 10)  : '\u0000');

    }

This what I have so far but when I output the string for array {0,-1,-1} rather than just getting the string "0" I'm getting string "0��".

does anyone know how I can get the result I want.

Thanks, m

like image 535
mAndroid Avatar asked Sep 29 '11 04:09

mAndroid


1 Answers

I'm going to assume you want to terminate the string at the first null character, as would happen in C. However, you can have null characters inside strings in Java, so they won't terminate the string. I think the following code will produce the behaviour you're after:

StringBuilder sb = new StringBuilder();
for (int i=0; i < mTypeSelection.length; i++){
    if(mTypeSelection[i] > -1) {
        sb.append(Character.forDigit(mTypeSelection[i], 10));
    } else {
        break;
    }
}
String result = sb.toString();
like image 69
Timothy Jones Avatar answered Sep 21 '22 05:09

Timothy Jones