Sprintf equivalent in Java

前端 未结 5 2053
小鲜肉
小鲜肉 2020-11-30 17:40

Printf got added to Java with the 1.5 release but I can\'t seem to find how to send the output to a string rather than a file (which is what sprintf does in C). Does anyone

5条回答
  •  抹茶落季
    2020-11-30 18:30

    Both solutions workto simulate printf, but in a different way. For instance, to convert a value to a hex string, you have the 2 following solutions:

    • with format(), closest to sprintf():

      final static String HexChars = "0123456789abcdef";
      
      public static String getHexQuad(long v) {
          String ret;
          if(v > 0xffff) ret = getHexQuad(v >> 16); else ret = "";
          ret += String.format("%c%c%c%c",
              HexChars.charAt((int) ((v >> 12) & 0x0f)),
              HexChars.charAt((int) ((v >>  8) & 0x0f)),
              HexChars.charAt((int) ((v >>  4) & 0x0f)),
              HexChars.charAt((int) ( v        & 0x0f)));
          return ret;
      }
      
    • with replace(char oldchar , char newchar), somewhat faster but pretty limited:

          ...
          ret += "ABCD".
              replace('A', HexChars.charAt((int) ((v >> 12) & 0x0f))).
              replace('B', HexChars.charAt((int) ((v >>  8) & 0x0f))).
              replace('C', HexChars.charAt((int) ((v >>  4) & 0x0f))).
              replace('D', HexChars.charAt((int) ( v        & 0x0f)));
          ...
      
    • There is a third solution consisting of just adding the char to ret one by one (char are numbers that add to each other!) such as in:

      ...
      ret += HexChars.charAt((int) ((v >> 12) & 0x0f)));
      ret += HexChars.charAt((int) ((v >>  8) & 0x0f)));
      ...
      

    ...but that'd be really ugly.

提交回复
热议问题