How to split the string after counting 50 characters

Asked

Viewed 265 times

1

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

I got it 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.

  • Do you have any specific criteria, or just take the first 50?

  • take the last space, before 50 characters, and place in a variable and the rest in a 2 variable

1 answer

1


You can do a little better, but the question does not give details. You need to pick up to the established limit where you have space. 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

Behold working in the .NET Fiddle. Also put on the Github for future reference.

  • @Sergioteixeira see now.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.