從字串中取一個字元作為數組元素

來源:互聯網
上載者:User

從字串中取一個字元作為數組元素
public class mainclass {

  public static void main(string[] arg) {
    string text = "to be or not to be";        // define a string
    byte[] textarray = text.getbytes();
   
    for(byte b: textarray){
      system.out.println(b);
     
    }
  }
 
給資料增加值

class substringcons {
  public static void main(string args[]) {
    byte ascii[] = { 65, 66, 67, 68, 69, 70 };

    string s1 = new string(ascii);
    system.out.println(s1);

    string s2 = new string(ascii, 2, 3);
    system.out.println(s2);
  }
}

轉換成位元組來一個十六進位字串


import java.io.unsupportedencodingexception;
/**
 * format validation
 *
 * this class encodes/decodes hexadecimal data
 * @author jeffrey rodriguez
 * @version $id: hexbin.java 125124 2005-01-14 00:23:54z kkrouse $
 */
public class main {
  static private final int  baselength   = 255;
  static private final int  lookuplength = 16;
  static private byte [] hexnumbertable    = new byte[baselength];
  static private byte [] lookuphexalphabet = new byte[lookuplength];


  static {
      for (int i = 0; i<baselength; i++ ) {
          hexnumbertable[i] = -1;
      }
      for ( int i = '9'; i >= '0'; i--) {
          hexnumbertable[i] = (byte) (i-'0');
      }
      for ( int i = 'f'; i>= 'a'; i--) {
          hexnumbertable[i] = (byte) ( i-'a' + 10 );
      }
      for ( int i = 'f'; i>= 'a'; i--) {
         hexnumbertable[i] = (byte) ( i-'a' + 10 );
      }

      for(int i = 0; i<10; i++ )
          lookuphexalphabet[i] = (byte) ('0'+i );
      for(int i = 10; i<=15; i++ )
          lookuphexalphabet[i] = (byte) ('a'+i -10);
  }

  /**
   * converts bytes to a hex string
   */
  static public string bytestostring(byte[] binarydata)
  {
      if (binarydata == null)
          return null;
      return new string(encode(binarydata));
  }
  /**
   * array of byte to encode
   *
   * @param binarydata
   * @return return encode binary array
   */
  static public byte[] encode(byte[] binarydata) {
      if (binarydata == null)
          return null;
      int lengthdata   = binarydata.length;
      int lengthencode = lengthdata * 2;
      byte[] encodeddata = new byte[lengthencode];
      for( int i = 0; i<lengthdata; i++ ){
          encodeddata[i*2] = lookuphexalphabet[(binarydata[i] >> 4) & 0xf];
          encodeddata[i*2+1] = lookuphexalphabet[ binarydata[i] & 0xf];
      }
      return encodeddata;
  }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.