How to split the string after counting 50 characters

1

I have to count 50 characters and make a split in two variables. The ideal would be to split in the last space before 50 characters. This is to be able to put the address on two lines in the database.

I have this like this:

Dim Morada As String = "Avenida luis de camoes, travessa de santa rita numero 588"
Dim CountMorada As Integer = Len(Morada)  'resultado de 57 carateres

I wanted to cut before number and put in two variables.

    
asked by anonymous 19.06.2017 / 23:33

1 answer

1

You can do a little better, but the question does not give details. You need to get to the limit where you have space. It has function ready for this ( LastIndexOf() ).

Imports System

Public Module Module1
    Public Sub Main()
        For Each texto in CropText("Avenida luis de camoes, travessa de santa rita numero 588", 50)
            Console.WriteLine(texto)
        Next
        For Each texto in CropText("Avenida luis de camoes, travessa de santa rita", 50)
            Console.WriteLine(texto)
        Next
        For Each texto in CropText("Avenidaluisdecamoes,travessadesantaritanumero588teste", 50)
            Console.WriteLine(texto)
        Next
    End Sub

    Public Function CropText(text As String, limit As Integer) As String()
        If text.Length < limit
            Return New String() {text}
        Else
            Dim position As Integer = text.LastIndexOf(" ", limit)
            If position = -1
                Return New String() {text}
            Else
                return New String() {text.Substring(0, position), text.Substring(position + 1)}
            End If
        End If
    End Function
End Module

See running on .NET Fiddle . And no Coding Ground . Also put it in GitHub for future reference a>.

    
20.06.2017 / 00:43