5

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

2
  • Can you provide the full code? How are you printing out the result? Commented Sep 29, 2011 at 4:44
  • 1
    Sounds like the behaviour you say you want is what's happening - you're ending up with null characters in positions 2 and 3 in the final string. Null characters don't terminate the string in Java. Are you wanting to truncate the string at the first -1 in the array? Commented Sep 29, 2011 at 4:59

1 Answer 1

6

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();
Sign up to request clarification or add additional context in comments.

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.