1.

Solve : VB add char after n chars?

Answer»

Hello guys,
I'm trying to make a PROGRAM that adds a character after n characters.
For example I'll insert the number 100000000000000 and I want that after each 5 characters to add a dot, like 10000.00000.00000
Can you give me a LINK or a code for this please?
Thank you.

Visual Basic 6:

Code: [Select]'Inserts 'Insert' Every Interval Characters in InputStr and returns the result.
Public Function EveryN(ByVal InputStr As String, ByVal Interval As Integer, ByVal Insert As String) As String
    'there are a few ways to do this, the most common is to iterate character by character, but that is rather slow, PARTICULARLY
    'since String concat is typically done a tad slowly on VB.
    'instead, we'll split the string into an array where each element holds Interval characters from the original string. Then
    'we can use the built in Join function to connect them together.
    Dim Strparts() As String
    Dim NumElements As Integer
    NumElements = (Len(InputStr) \ Interval) + Abs((Len(InputStr) MOD Interval > 0))
    ReDim Strparts(NumElements - 1)
    Dim I As Long
    Dim StartPos As Long
    For I = 0 To NumElements - 1
       StartPos = (I * Interval) + 1
       Strparts(I) = Mid$(InputStr, StartPos, Interval)
   
   
    Next I
   
    EveryN = Join(Strparts, Insert)


End Function

Sample Usage:

Code: [Select]Dim Strtest As String
Dim I As Long, J As Long
For I = 0 To 10
    For J = 0 To 9
        Strtest = Strtest + Trim$(Str$(J))
Next J, I

Dim result As String
result = EveryN(Strtest, 5, ",")
MsgBox (result)


Visual Basic .NET:


Code: [Select]    Public Function EveryN(ByVal InputStr As String, ByVal Interval As Integer, ByVal Insert As String) As String
        Dim NumElements As Integer
        NumElements = (Len(InputStr) \ Interval) + IIf((Len(InputStr) Mod Interval > 0), 1, 0)
        Dim strbuild As New System.Text.StringBuilder
        Dim I As Long, useLength As Integer = Interval
        Dim StartPos As Long
        For I = 0 To NumElements - 1

            StartPos = (I * Interval)
            If (InputStr.Length - StartPos < Interval) Then
                strbuild.Append(InputStr.Substring(StartPos))
            Else
                strbuild.Append(InputStr.Substring(StartPos, Interval))
            End If
            If I < NumElements - 1 Then strbuild.Append(",")


        Next I

        Return strbuild.ToString()


    End Function

Sample usage:

Code: [Select]   Sub Main()
        Dim Strtest As String = String.Empty
        Dim I As Long, J As Long
        For I = 0 To 10
            For J = 0 To 9
                Strtest += Trim$(Str$(J))
        Next J, I
        Dim result As String
        result = EveryN(Strtest, 5, ",")
        Console.WriteLine(result)
        Console.ReadKey()
    End Sub


Also, if you just want standard, decimal after 3 characters, you can use Format(number,"#,###")



Discussion

No Comment Found