How to declare a fixed-length string in VB.NET?

前端 未结 10 2851
醉酒成梦
醉酒成梦 2020-12-10 04:27

How do i Declare a string like this:

Dim strBuff As String * 256

in VB.NET?

相关标签:
10条回答
  • 2020-12-10 04:43

    Use stringbuilder

    'Declaration   
    Dim S As New System.Text.StringBuilder(256, 256)
    'Adding text
    S.append("abc")
    'Reading text
    S.tostring
    
    0 讨论(0)
  • 2020-12-10 04:46
    Dim a as string
    
    a = ...
    
    If a.length > theLength then
    
         a = Mid(a, 1, theLength)
    
    End If
    
    0 讨论(0)
  • 2020-12-10 04:53

    To write this VB 6 code:

    Dim strBuff As String * 256
    

    In VB.Net you can use something like:

    Dim strBuff(256) As Char
    
    0 讨论(0)
  • 2020-12-10 04:54

    This object can be defined as a structure with one constructor and two properties.

    Public Structure FixedLengthString
         Dim mValue As String
         Dim mSize As Short
    
         Public Sub New(Size As Integer)
             mSize = Size
             mValue = New String(" ", mSize)
         End Sub
    
         Public Property Value As String
             Get
                 Value = mValue
             End Get
    
             Set(value As String)
                 If value.Length < mSize Then
                     mValue = value & New String(" ", mSize - value.Length)
                 Else
                     mValue = value.Substring(0, mSize)
                 End If
             End Set
         End Property
     End Structure
    

    https://jdiazo.wordpress.com/2012/01/12/getting-rid-of-vb6-compatibility-references/

    0 讨论(0)
  • 2020-12-10 04:56

    Try this:

        Dim strbuf As New String("A", 80)
    

    Creates a 80 character string filled with "AAA...."'s

    Here I read a 80 character string from a binary file:

        FileGet(1,strbuf)
    

    reads 80 characters into strbuf...

    0 讨论(0)
  • 2020-12-10 04:57

    It depends on what you intend to use the string for. If you are using it for file input and output, you might want to use a byte array to avoid encoding problems. In vb.net, A 256-character string may be more than 256 bytes.

    Dim strBuff(256) as byte
    

    You can use encoding to transfer from bytes to a string

    Dim s As String
    Dim b(256) As Byte
    Dim enc As New System.Text.UTF8Encoding
    ...
    s = enc.GetString(b)
    

    You can assign 256 single-byte characters to a string if you need to use it to receive data, but the parameter passing may be different in vb.net than vb6.

    s = New String(" ", 256)
    

    Also, you can use vbFixedString. I'm not sure exactly what this does, however, because when you assign a string of different length to a variable declared this way, it becomes the new length.

    <VBFixedString(6)> Public s As String
    s = "1234567890" ' len(s) is now 10
    
    0 讨论(0)
提交回复
热议问题