Separate a string

Z

Ze Coder

Hello, I would like to know how to split a string variable in x
lines(possibly an array) of a maximum length of 30 chrs, but without
truncating words.

I Think there's a trick to do with substring, but don't know much.

Thanks to help me on this issue,

Sebastien
 
R

Ronchese

dim arrString() as string

'this code splits your string in a array, word by word, separated by space:
arrString = "your string".split(" ")


If you need your string be approximated to 30 chars, you can do some loops
and concatenate the array elements on a second array. For sample:

Dim i As Integer
Dim strLine As String
Dim arrString2() As String
Dim intUboundStr2 As Integer = -1

'transfer all strings from first array, to second array,
'trying to limite each line till 30 characters
For i = 0 To arrString.Length - 1
If Len(strLine & arrString(i)) <= 30 Then
strLine = strLine & " " & arrString(i)
Else
intUboundStr2 = intUboundStr2 + 1
ReDim Preserve arrString2(intUboundStr2)
arrString2(intUboundStr2) = strLine
strLine = ""
End If
Next
'transfer the eventual remanescent characters
If strLine <> "" Then
intUboundStr2 = intUboundStr2 + 1
ReDim Preserve arrString2(intUboundStr2)
arrString2(intUboundStr2) = strLine
End If
End Sub


Note: you can use StringBuilder class to eventually help your code speed up,
incase you are working with large strings.


[]s
Cesar




"Ze Coder" <[email protected]> escreveu na mensagem
Hello, I would like to know how to split a string variable in x
lines(possibly an array) of a maximum length of 30 chrs, but without
truncating words.

I Think there's a trick to do with substring, but don't know much.

Thanks to help me on this issue,

Sebastien
 
C

Cor Ligthert [MVP]

Ze,

Another method than Ronchese avoiding the redim which is eating resources in
his sample.
(Ronchese uses a classic VB approach, with what is nothing wrong except than
that Redim is not so lucky).

It is typed in this message and not tested so watch typos or whatever

\\\
Dim startpoint as integer
dim stringlength as integer = mystring.length
dim count as integer = stringlength \ 30
dim ar as new arraylist
For i as integer = 0 to count
ar.add(mystring.substring(startpoint,30))
startpoint =+ 30
next
ar.add(mystring.substring(startpoint)
///

I hope this helps,

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top