开发者

Java null char in string

开发者 https://www.devze.com 2023-04-09 20:32 出处:网络
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

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 arr开发者_Go百科ay {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();
0

精彩评论

暂无评论...
验证码 换一张
取 消