CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jan 2001
    Posts
    2

    Partition as string

    How can I partition a string that can be longer than 25 marks in 2 variables. Each variable should have complete words.

    AngieB

  2. #2
    Join Date
    Jul 2000
    Location
    Milano, Italy
    Posts
    7,726

    Re: Partition as string

    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.
    ...at present time, using mainly Net 4.0, Vs 2010



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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured