【问题标题】:Find the position of the last english character in a stream查找流中最后一个英文字符的位置
【发布时间】:2013-08-19 13:56:10
【问题描述】:

我有一个阅读器,它以流(ByteArrayInputStream)的形式接收消息包。
每个数据包都包含由英文字符和二进制数字组成的数据。

adghfjiyromn1000101010100......

从这个流中复制(而不是剥离)字符作为序列的最有效方法是什么。 因此,上述数据包的预期输出将是(不修改原始流):

adghfjiyromn

我不仅关心逻辑,还关心要使用的确切流操作例程;考虑到读者假设每秒会读取大约 3-4 个数据包。
它还有助于说明为什么我们更喜欢使用特定数据类型(byte[]、char[] 或 string)来解决这个问题。

【问题讨论】:

  • 请给出输入和预期输出。

标签: java character-encoding inputstream


【解决方案1】:

您:每个数据包都包含由英文字符和二进制数字组成的数据。 我:数据在 bytearrayinputstream 中,因此一切都是二进制的。 你的 1000101010100……是字符 '1' & '0' 吗?

如果是的话

ByteArrayInputStream msg =  //whatever
        int totalBytes = msg.available();
        int c;
        while ((c = msg.read())!= -1) {
          char x = (char) c;
          if (x=='1' || x=='0') break;
        }
        int currentPos = msg.available() + 1; //you need to unread the 1st 0 or 1
        System.out.println("Position = "+(totalBytes-currentPos));

【讨论】:

    【解决方案2】:

    我认为最好的方法是逐字节读取 ByteArrayInputStream:

    ByteArrayInputStream msg = ...
    int c;
    String s;
    while ((c = msg.read())!= -1) {
      char x = (char) c;
      if (x=='1' || x=='0') break;
      s += x;
    }
    

    【讨论】:

      【解决方案3】:

      我认为这是最好的方法:

      1-将您的 ByteArrayInputStream 转换为字符串(或 StringBuffer) 2-找到第一个 0 或 1 的索引 3-使用子字符串(0,FIRST_INDEX)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        • 2014-09-19
        • 1970-01-01
        • 2013-01-04
        • 2019-09-22
        相关资源
        最近更新 更多