Java ASCII控制代码为文字值

时间:2013-05-17 12:46:45

标签: java arrays integer character

我在这里可能有些愚蠢,但我似乎无法想到解决这个问题的直接解决方案。

我目前有一个包含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

正如您所看到的,数组中的最后两个条目是空白的,因为实际上没有4或31的ASCII字符。我知道有将Strings转换为{{1}的方法但是,当你已经得到一个你想要价值的char []时,一般的想法是什么。

这可能是一个非常简单的解决方案,我想我只是有一个愚蠢的时刻!

任何建议都会很感激,谢谢!

char[]

2 个答案:

答案 0 :(得分: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);
    }
  }
}

答案 1 :(得分: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
    }
}