一个字符长度的问题,帮助我吧
我写了一个程序,功能是输出文本并要求每列对齐比如输出3列:[name] [age]
老王 20
a 18
我设定了每列数据的固定长度是5,
比如第1行第1列的“老王 ”,加上“老王”后面的空格总长度为5
第2行第1列的“a ”,加上空格总长度也是5,
但这样输出到文本文件,[name]列后面的[age]列的数据会出现如上不对齐的情况,我想要对齐
怎么办呢,该怎么处理。求教
SOS --------------------编程问答-------------------- 用窗体的.TextWidth属性计算长度,再换算出要加几个空格 --------------------编程问答-------------------- 你的做法不对,应该是这样
先用lenb ( strconv( "老王", vbfromunicode ) )算出来一个结果,再用 string( ) 函数对齐。
--------------------编程问答--------------------
Option Explicit--------------------编程问答--------------------
Private Function myAlign(ByVal str1 As String, ByVal str2 As String, ByVal spaces As Long) As String
On Error GoTo errhandle
Dim s As String
s = str1 & String(spaces - LenB(StrConv(str1, vbFromUnicode)), " ") & str2
myAlign = s
Exit Function
errhandle:
Err.Clear
End Function
Private Sub Command1_Click()
Debug.Print myAlign("汉字", "英文", 20)
Debug.Print myAlign("汉字111", "fdsa", 20)
Debug.Print myAlign("222", "英文", 20)
Debug.Print myAlign("54325423", "英5432文", 20)
Debug.Print myAlign("汉5432字", "英654文", 20)
Debug.Print myAlign("6543汉字", "5432英文", 20)
Debug.Print myAlign("汉字54325", "英5432文", 20)
Debug.Print myAlign("汉xxx字", "54325423", 20)
Debug.Print myAlign("汉xx字", "54325423", 20)
Debug.Print myAlign("xx汉字", "5423", 20)
Debug.Print myAlign("汉xx字", "xcxxxx", 20)
Debug.Print myAlign("汉x字", "bbb", 20)
Debug.Print myAlign("xxxxxxxxxx", "bbbbbbbbb", 20)
End Sub
Option Explicit--------------------编程问答-------------------- 用Tab对齐 不好吗? 计算空格 不嫌烦啊!! --------------------编程问答-------------------- 每个字符后面留的空格数不一样,空格数等于用5减去每个数据所占用的字节数 lenb ( strconv( "老王", vbfromunicode ) ) --------------------编程问答-------------------- 想对齐, 用TAB是最科学的啦:)
Private Function myAlign(ByVal str1 As String, ByVal str2 As String, ByVal spaces As Long) As String
On Error GoTo errhandle
Dim s As String
s = str1 & String(spaces - LenB(StrConv(str1, vbFromUnicode)), " ") & str2
myAlign = s
Exit Function
errhandle:
Err.Clear
End Function
Private Sub Command1_Click()
Debug.Print myAlign("[name]", "[age]", 20)
Debug.Print myAlign("老大", "15", 20)
Debug.Print myAlign("张三", "20", 20)
Debug.Print myAlign("Jenny", "4", 20)
Debug.Print myAlign("Fiona", "2", 20)
End Sub
Open "实验.txt" For Binary As #1
Put #1, , "老王" & vbTab
Put #1, , 20 & vbTab
Put #1, , vbCrLf
Put #1, , "a" & vbTab
Put #1, , 18 & vbTab
Put #1, , vbCrLf
Close
补充:VB , 基础类