Home > Back-end >  covert textbox value to [3x][3x][3x]
covert textbox value to [3x][3x][3x]

Time:07-25

I need a way to convert textbox value into following format:

enter image description here

it should return back Eight [xx],[30] at beginning if digit does not exist on that place and [3x] for the place where digit exist

I have written the following code:

Imports System.Text

Dim number As Integer = "1234527"
    Dim finalres As StringBuilder = New StringBuilder()
    Dim res As Integer() = {30, 30, 30, 30, 30, 30, 30, 30}
    With Nothing
        Dim i As Integer = 7
        While i >= 0
            If (number > 0) Then
                Dim [rem] As Integer = number Mod 10
                number = (number / 10)
                Dim n As Integer = 30   [rem]
                Dim s As String = "["   n.ToString()   "]"
                finalres.Insert(0, s)
            Else
                finalres.Insert(0, "["   30.ToString()   "]")
            End If
            Math.Max(Threading.Interlocked.Decrement(i), i   1)
End While
End With
Console.WriteLine(String.Join(", ", finalres))

MsgBox(finalres.ToString)

but this is returning some output right and some wrong, for example in this case when number = 1234527, it is returning [30][31][32][33][34][35][33][37] whereas my desired output is [30][31][32][33][34][35][32][37]

CodePudding user response:

Firstly to deal with the error in your code. You are sometimes seeing incorrect results because of rounding when you do integer division. The solution is to remove the remainder before dividing by 10. Change the relevant line to:

number = ((number - [rem]) / 10)

However the task can be achieved far more simply, if you convert the entire integer to a string, using PadLeft to add any required 0s. Then all you have to do is loop through the resultant 8 character string like this:

Dim number As Integer = 1234527
Dim strNumber As String = number.ToString.PadLeft(8, "0")

Dim finalres As StringBuilder = New StringBuilder()
For i As Integer = 0 To 7
    finalres.Append("[3"   strNumber(i)   "]")
Next

MessageBox.Show(finalres.ToString)

By way of explanation, PadLeft can take a second parameter specifying the character to be used for the padding, in this case 0.

Any string can be treated as an Array, so that you can refer to the individual characters within the string by their (0 based) index position.

  • Related