Truncating Strings by Bytes

后端 未结 13 1729
醉酒成梦
醉酒成梦 2021-02-06 04:21

I create the following for truncating a string in java to a new string with a given number of bytes.

        String truncatedValue = \"\";
        String curren         


        
13条回答
  •  一生所求
    2021-02-06 04:50

    Binary search approach in scala:

    private def bytes(s: String) = s.getBytes("UTF-8")
    
    def truncateToByteLength(string: String, length: Int): String =
      if (length <= 0 || string.isEmpty) ""
      else {
        @tailrec
        def loop(badLen: Int, goodLen: Int, good: String): String = {
          assert(badLen > goodLen, s"""badLen is $badLen but goodLen is $goodLen ("$good")""")
          if (badLen == goodLen + 1) good
          else {
            val mid = goodLen + (badLen - goodLen) / 2
            val midStr = string.take(mid)
            if (bytes(midStr).length > length)
              loop(mid, goodLen, good)
            else
              loop(badLen, mid, midStr)
          }
        }
    
        loop(string.length * 2, 0, "")
      }
    

提交回复
热议问题