0

ここで私はややばかげているかもしれませんが、この問題に対する簡単な解決策を思いつかないようです。

現在、ASCII 文字コードを含む int[] を取得していますが、ASCII テーブルでは、32 未満の値はすべて制御コードです。したがって、32を超える値の場合はASCII文字をchar []に入れる必要がありますが、32未満の場合は、リテラル整数値を文字として入れるだけです。

例えば:

public static void main(String[] args) {
    int[] input = {57, 4, 31}; //57 is the only valid ASCII character '9'
    char[] output = new char[3];

    for (int i = 0; i < input.length; i++) {
        if (input[i] < 32) { //If it's a control code
            System.out.println("pos " + i + " Not an ascii symbol, it's a control code");
            output[i] = (char) input[i];
        } else { //If it's an actual ASCII character
            System.out.println("pos " + i + " Ascii character, add to array");
            output[i] = (char) input[i];
        }
    }

    System.out.println("\nOutput buffer contains:");
    for (int i = 0; i < output.length; i++) {
        System.out.println(output[i]);

    }
}

出力は次のとおりです。

pos 0 Ascii character, add to array
pos 1 Not an ascii symbol, it's a control code
pos 2 Not an ascii symbol, it's a control code

Output buffer contains:
9 // int value 57, this is OK

Stringsご覧のとおり、配列の最後の 2 つのエントリは空白です。これは、実際には 4 または 31 の ASCII 文字が存在しないためchar[]です。値が必要な char[]。

これにはおそらく本当に簡単な解決策があります。私はただ愚かな瞬間を過ごしていると思います!

アドバイスをいただければ幸いです。


4

2 に答える 2

1

文字を分類するには、Character.getType(char)メソッドを使用する必要があります。

文字または整数のいずれかを格納するには、ラッパー オブジェクトを使用してそれを行うことができます。

charまたは、次のようにラップすることもできます。

static class NiceCharacter {
  // The actual character.
  final char ch;

  public NiceCharacter ( char ch ) {
    this.ch = ch;
  }

  @Override
  public String toString () {
    return stringValue(ch);
  }

  public static String stringValue ( char ch ) {
    switch ( Character.getType(ch)) {
      // See http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters for what the Cc group is.
      // See http://en.wikipedia.org/wiki/Control_character for a definition of what  are CONTROL characters.
      case Character.CONTROL:
        return Integer.toString(ch);

      default:
        return Character.toString(ch);
    }
  }
}
于 2013-05-17T12:53:10.483 に答える
0

出力バッファの印刷方法を変更する

for (int i = 0; i < output.length; i++) {
    if (output[i] < 32){
        System.out.println("'" + (int)output[i] + "'"); //Control code is casted to int.
        //I added the ' ' arround the value to know its a control character
    }else {
        System.out.println(output[i]); //Print the character
    }
}
于 2013-05-17T12:57:24.387 に答える