简体   繁体   中英

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM