[VB]byte数组和string相互转换

作者在 2008-02-29 08:17:52 发布以下内容
在vb里,byte数组和string可以互相赋值,利用这个特性处理字符串非常方便。  
   
  如果是处理大量文本,以下用法应该熟悉。  
   
  字符串与byte数组互相赋值:  
  tbytes()=tstring  
  tstring=tbytes()  
   
  需要注意的是,在vb内部字符串是unicode表示的,而asc函数返回的是ascii和gbk编码。因此,asc函数返回的编码值与上面的byte数组返回的值可能是不同的。  
   
  从ascii/gbk文本获得unicode数组:  
  tbytes()=strconv(tstring,vbunicode)  
   
  从unicode文本获得ascii/gbk数组:  
  tbytes()=strconv(tstring,vbformunicode)  
   
  从ascii/gbk数组获得unicode文本:  
  tstring=strconv(tbytes(),vbunicode)  
   
  从unicode数组获得ascii/gbk文本:  
  tstring=strconv(tbytes(),vbformunicode)  
   
  快速读取文本文件:  
   
  将文本文件整个读到byte数组:  
  dim   tbytes()   as   byte  
  tfn=freefile  
  open   pfilename   for   binary   as   #tfn  
      tfilesize=lof(#tfn)  
      redim   tbytes(tfilesize-1)  
      get   #tfn,1,tbytes()  
  close   #tfn  
  tstring=strconv(tbytes(),vbunicode)   从文件获得数组转换为带换行的多行文本字符串。  
   
  反之,如果将字符串文本写为二进制文件,则要:  
  dim   tbytes()   as   byte  
  tbytes()=strconv(tstring,vbformunicode)  
   
  tfn=freefile  
  open   pfilename   for   output   as   #tfn   清除文件内容  
  close   #tfn  
  open   pfilename   for   binary   as   #tfn  
      put   #tfn,1,tbytes()  
  close   #tfn  
   
  另外,还可以用api函数copymemory将byte数组转换为integer数组,在利用查表法进行内码转换、简繁转换时,该操作尤为重要。因为,在vb当中,每个“字”的编码都是16位unicode,用integer数组表示最为直观。但integer数组不能直接与string赋值,因此需要一个与byte数组转换的过程。  
默认分类 | 阅读 31560 次
文章评论,共0条
游客请输入验证码