Click to See Complete Forum and Search --> : Partition as string


AngieB
May 25th, 2001, 05:16 AM
How can I partition a string that can be longer than 25 marks in 2 variables. Each variable should have complete words.

AngieB

Cimperiali
May 25th, 2001, 05:52 AM
Here an example you may use as starting point or improve (this works, but you may optimize, and make some more controls for errors handling)

Option Explicit

Private Sub Command1_Click()
'How can I partition a string that
'can be longer than 25 marks in 2 variables.
'Each variable should have complete words

Dim strFirst As String 'your starting string

Dim intLenFirst As Integer 'len of your starting string

Dim intForwardPos As Integer 'position of found blank

Dim intBackwardPos As Integer 'same as above, but from middle string to beginning

Dim strVarA As String 'your first resulting variable

Dim strVarB As String 'your second resulting variable

strFirst = "A long long string to split into two variables around about the half"
intLenFirst = Len(strFirst)
'be sure it is more than 1 char
If intLenFirst > 1 Then
'now, staring from half of value of your string,
'search for a blank value to split the string
intForwardPos = InStr(intLenFirst / 2, strFirst, " ", vbTextCompare)
intBackwardPos = InStrRev(strFirst, " ", intLenFirst / 2, vbTextCompare)
'be sure you find a space!
If intForwardPos <> 0 Or intBackwardPos <> 0 Then
'which is nearer to half of string?
If intForwardPos - intLenFirst / 2 > intLenFirst / 2 - intBackwardPos Then
'nearest is in backward
strVarA = Mid(strFirst, 1, intBackwardPos - 1)
strVarB = Mid(strFirst, intBackwardPos + 1, intLenFirst)
Else
'nearest is in foreward
strVarA = Mid(strFirst, 1, intForwardPos - 1)
strVarB = Mid(strFirst, intForwardPos + 1, intLenFirst)
End If 'which nearest the half
End If 'at least a space found
End If 'len of string bigger than 1
MsgBox strVarA & " len is:" & Len(strVarA) & vbCrLf & strVarB & " len is:" & Len(strVarB)
End Sub



Special thanks to Lothar "the Great" Haensler, Tom Archer, Chris Eastwood, Bruno Paris and all the other wonderful people who made and make Codeguru a great place. Come back soon, you Gurus.